문제

I'm trying to make my Python script stream its output to my webpage as its printed.

So in my javascript I do:

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();

and in my Python script I have:

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()

Now I expect 0 1 2 3 4, but what I get is 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4

It seems to be sending the whole buffer each time, when what I really want is for it to send one digit per onreadystatechange.

What am I doing wrong?

도움이 되었습니까?

해결책

xmlhttp.responseText on the client side always contains the entire response, so you don't need newbody, just use xmlhttp.responseText.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top