Ajax与php,获得状态200但readyState 0

Ajax与php,获得状态200但readyState 0

问题描述:

Script:

function ajaxHandler() {
    var xmlhttp;
    try {  // Opera 8.0+, Firefox, Safari
       xmlhttp = new XMLHttpRequest();

    } catch (e) {   // Internet Explorer Browsers
   try {
        alert("paososdao");
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
      try{ 
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {   // Something went wrong
         alert("Your browser broke!");
         return false;
      }
   }
 }
    xmlhttp.onreadystatechange = useHttpResponse();
    xmlhttp.open("GET","prova.php",true); 
    xmlhttp.send(null);

    function useHttpResponse(){ 
        if (xmlhttp.readyState < 4)                         // while waiting response from server
            document.getElementById('test').innerHTML = "Loading...";
        else if (xmlhttp.readyState === 4) {             
            if (xmlhttp.status == 200 && xmlhttp.status < 300)
                document.getElementById('test').innerHTML = xmlhttp.responseText;

       }
    }
}

I'm testing it using xampp and I always get readyState = 0 and no response from prova.php, but if I open the developer console on Chrome I can see that the GET request status is 200. What's the problem.

Try that:

 xmlhttp.onreadystatechange = useHttpResponse;

You're calling the useHttpResponse before you need it.