我正在尝试使我的 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 发送一个数字。
我究竟做错了什么?