2012-11-29 126 views
3

我正在關注w3schools上的PHP/AJAX教程,並且我在一行中遇到了一些障礙。每次我調用這個函數時,readystate總是未定義的。XMLHttpRequest ReadyState始終未定義

function showHint(str) { 
    if (str.length == 0) { 
     document.getElementById("txtHint").innerHTML = ""; 
      return; 
     } 

     var xmlhttp; 

     if (window.XMLHttpRequest) { 
      console.log("Using XMLHttpRequest"); 
      xmlhttp = new XMLHttpRequest(); 
     } 
     else { 
      console.log("Using ActiveXObject"); 
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 

     xmlhttp.open("GET", "gethint.php?q=" + str, true); 
     xmlhttp.send(); 

     xmlhttp.onreadystatechange = function() { 
     console.log(xmlhttp.readystate); 

     if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { 
      console.log(xmlhttp.status); 
      document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
     } 
    } 
} 

如果我改變這一行:

if (xmlhttp.readystate == 4 && xmlhttp.status == 200) { ... 

這(通過錯字):

if (xmlhttp.readystate = 4 && xmlhttp.status == 200) { ... 

然後,它的工作原理,但像 「奇蹟發生在這裏」 感覺那種要編寫這樣的代碼。

+1

'xmlhttp.readystate = 4'(單等號,分配)分配'4'到'.readystate'屬性和是取值爲'4'的表達,這是一種'truthy'值並因此通過if檢查。所以它可能是'if(true && xmlhttp.status == 200)'或者只是'if(xmlhttp.status == 200)' – Esailija

回答

13

JS區分大小寫。您需要檢查readyState屬性,而不是readystate屬性。

if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 
     console.log(xmlhttp.status); 
     document.getElementById("txtHint").innerHTML = xmlhttp.responseText; 
    } 
+4

另外,'readyState'不應該是'undefined'。它在創建對象時從零開始,因此獲得「未定義」是錯誤的一個很好的標誌。 –

+0

@PaulButcher當status是任何類似'404'的錯誤代碼時,readyState返回'undefined'。 –