im using a python script to display text to the screen with ajax but it’s laggy and sometimes not even working..
here’s the python script
#!/usr/bin/env python
import cgi, cgitb
form = cgi.FieldStorage()
q = form.getvalue('q')
print "Content-Type: text/html\n"
print q
and the html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function show(str){
var xmlhttp;
if (str.length == 0){
document.getElementById("hint").innerHTML = "";
return;
}
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../cgi-bin/ajax_test.py?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form action="">
<input type="text" id="txt1" onkeyup="show(this.value)" />
</form>
<span id="hint"></span>
</body>
is it my code’s fault? or is it because cgi/python is slow?
While your example works just fine for me on a local OSX apache server, I would suggest that using python CGI as a backend solution to serving ajax calls would be highly inefficient. The very nature of CGI means that every single request has to spawn a process of that python script.
http://en.wikipedia.org/wiki/Common_Gateway_Interface
While it may function just fine locally, with just you doing tests, it will be much more impacted when you make it public facing, with multiple clients connecting.
wsgi (or at least fastcgi) is a far superior approach to old school CGI scripts. You could use mod_wsgi if you are using apache. There is also uwsgi, gunicorn, and many other approaches I am sure. Ultimately the idea is that instead of having a stand alone script that is called for every request, you have a persistant process that is running, accepting requests, and executing functions.
These days I think people just use the python CGI module as a learning step to writing server-side web code via python. You may want to consider moving over to a framework.