2012-07-11 133 views
1

我有這樣的代碼:阿賈克斯xmlhttp.onreadystatechange功能

function loadRegions() 
{ 
    var xmlhttp; 

    if (window.XMLHttpRequest) 
    {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
    } 
    else 
    {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    xmlhttp.onreadystatechange=function() 
    { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
     { 
      alert("Ready:"+xmlhttp.status); 
      xmlDoc=xmlhttp.responseXML; 
      x=xmlDoc.getElementsByTagName("region"); 
      alert(x[0]); 
      alert(x[1]); 
     } 
    } 

    var ctrcode = frm.elements['countrycode']; 
    xmlhttp.open("GET","http://mydomain.gr/regionslist.php?countrycode="+ctrcode.value,true); 
    xmlhttp.send(); 
} 

我有一個select項目在我的HTML,當有人選擇一個項目,然後調用此函數來獲得這個國家的地區。我可以從控制檯看到請求已完成,但響應從未得到。我的onreadystatechange函數永遠不會被調用。當我刪除xmlhttp.status==200時,函數被調用,但xmlDoc對象是nullxmlhttp.status==0。如果我單獨調用它,我使用的URL有效。爲什麼我的onreadystatechange函數不起作用,爲什麼它不返回狀態200?

回答

0

調用發送前加入這一行()函數:

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 

,也可以設置的onreadystatechange函數調用open()

原因後:
1)responseXML屬性表示當XML響應當內容類型標題指定MIME(媒體)類型爲text/xml,application/xml或以+ xml結尾時,已收到完整的HTTP響應(當readyState爲4時)。如果Content-Type標頭不包含這些媒體類型之一,則responseXML值爲null。
2)初始響應後,所有事件偵聽器都將被清除。在設置onreadystatechange偵聽器之前調用open()。
這裏是與first的引用second原因

+0

原因: 1)responseXML屬性代表當完整的HTTP響應已被接收到的XML響應(當readyState爲4),當所述Content-Type頭指定MIME(媒體)類型爲text/xml,application/xml,或以+ xml結尾。如果Content-Type標頭不包含這些媒體類型之一,則responseXML值爲null。 2)初始響應後,所有事件監聽器都將被清除。 在設置onreadystatechange偵聽器之前調用open()。 – 2012-07-11 11:26:52

+0

這裏是[第一個](http://www.oxymoronical.com/experiments/apidocs/interface/nsIXMLHttpRequest)和[第二個]的參考文獻(http://www.devx.com/webdev/Article/33024/ 1954)理由 – 2012-07-11 11:27:31

+1

看起來你的兩條評論更適合你的答案。這將把所有的信息放在一個地方,允許進一步的編輯,並允許更準確的投票和答案接受。其他用戶將看到答案中的所有信息,這是投票期間考慮的內容。 – 2012-07-12 02:51:46