Ajax重新发送XMLHttpRequest

I've got a client side js/ajax script like this:

<p>server  time  is:  <strong  id="stime">Please  wait...</strong></p>

<script>
function  updateAjax()  {
    xmlhttp  =  new  XMLHttpRequest();
    xmlhttp.onreadystatechange  =  function()  {
        if (xmlhttp.readyState==3  &&  xmlhttp.status==200)  {
            document.getElementById("stime").innerHTML=
            xmlhttp.responseText;
        }
        if  (xmlhttp.readyState==4)  {  
            xmlhttp.open("GET","date-sleep.php",true);
            xmlhttp.send();
        }
    }
    xmlhttp.open("GET","date-sleep.php",true);  
    xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>

And a on the server side:

<?php
    echo  6;
    for  ($i=0;  $i<10;  $i++)  {
        echo  $i;
        ob_flush();  flush();
        sleep(1);
    }
?>

After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.

Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.

Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.

if  (xmlhttp.readyState==4) {  
     updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}

I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:

if (xmlhttp.readyState==4  &&  xmlhttp.status==200) {
       document.getElementById("stime").innerHTML=
       xmlhttp.responseText;
       updateAjax(); //or setTimeout("updateAjax();",100);
}

Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:

var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");

I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.