我将尝试让我的Python脚本在输出时即时地流到网页上。因此,在我的Javascript中,我这样做:
var xmlhttp;
var newbody = "";
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==3) {
newbody = newbody + xmlhttp.responseText;
document.getElementById("new").innerHTML=newbody;
}
}
xmlhttp.open("GET","http://localhost/cgi-bin/temp.py",true);
xmlhttp.send();
在我的Python脚本中,我有以下代码:
print "Content-Type: text/plain"
print ""
print " " * 5000 # garbage data for safari/chrome
sys.stdout.flush()
for i in range(0,5):
time.sleep(.1)
sys.stdout.write("%i " % i)
sys.stdout.flush()
现在我期望的是0 1 2 3 4
,但实际上得到的是0 0 1 0 1 2 0 1 2 3 0 1 2 3 4
每次似乎发送整个缓冲区,而我真正想要的是每个 onreadystatechange 只发送一个数字。
我做错了什么?
sys.stdout.flush()
运行它吗?如果尝试过,结果是什么? - brandizzi