2014-09-20 61 views
0

爲什麼我總是得到XMLHttpRequest readystate而不是4 我也打印它在警報框它始終顯示從1,2,3 即時運行順序請檢查並讓我知道任何建議或建議,熱忱歡迎XMLHttRequest readystate不顯示4

var xmlHttp; 
xmlHttp = CreateXMLHttpRequestObject(); 

function CreateXMLHttpRequestObject() { 
    var isValidObj = true; 

    if (window.ActiveXObject) { 
     try { 
      xmlHttp = new ActiveXObject(); 
     } 
     catch (ex) { 

      isValidObj = false; 
     } 
    } 
    else { 
     if (window.XMLHttpRequest) { 
      try { 
       xmlHttp = new XMLHttpRequest(); 
      } 
      catch (ex) { 

       isValidObj = false; 
      } 


     } 
    } 
    if (!isValidObj) { 
     alert("Your browser do not support ajax"); 

    } 
    return xmlHttp; 

} 

function Process() { 
    if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) { 

     var food = encodeURIComponent(document.getElementById('txtFood').value); 
     xmlHttp.open("GET", "Default.aspx?food=" + food, true) 
     xmlHttp.onreadystatechange = handleServerResponse; 
     xmlHttp.send(); 
    } 

} 
function handleServerResponse() { 
    if (xmlHttp.readyState == 4) { 
     if (xmlHttp.status == 200) { 
      var strResponse = xmlHttp.responseText; 
      document.getElementById("divResult").innerHTML = "<span style='color:blue'>" + strResponse + " </span>"; 
      setTimeout('process()', 1000) 
     } 
    } 
    else { 
     alert(xmlHttp.readyState); 

    } 
} 

回答

0

您的代碼應根據本想我不需要你的過程中()函數 xmlhttp.onreadystatechange事件上的每個狀態變化自動調用。

var food = encodeURIComponent(document.getElementById('txtFood').value); 

xmlhttp.onreadystatechange=function() 
{ 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
     var strResponse = xmlHttp.responseText; 
     document.getElementById("divResult").innerHTML = "<span style='color:blue'>" + strResponse + " </span>"; 
    } 
    else 
    { 
    alert(xmlHttp.readyState); 
    } 
} 

xmlHttp.open("GET", "Default.aspx?food=" + food, true); 
xmlHttp.send(); 
+0

如何在onreadystatechange事件處理程序之後使用open方法? – 2014-09-22 05:07:56