2008-12-31 109 views
2

由於某種原因,onreadystatechange回調函數未在異步模式下調用。我在同步模式下測試了帖子,並確認帖子本身工作正常(註釋掉我用於在同步模式下查看帖子的測試代碼)。 safari和firefox最新版本都會出現這個問題。有人能告訴我我在這裏做錯了嗎?謝謝。onreadystatechange函數未被調用

<html> 
    <head> 
    <script> 
    function recordScore(str) 
    { 

    if (str.length==0) 
    { 

     return; 
    } 

    xmlHttp=GetXmlHttpObject(); 
    if (xmlHttp==null) 
    { 
     alert ("Your browser does not support AJAX!"); 
     return; 
    } 

    var url="http://hellworld3.appspot.com/findcountry"; 
    var params = "screenname="+document.getElementById("screenname1").value+"&score="+document.getElementById("score1").value; 
    alert("params: "+params); 
    xmlHttp.open("POST",url,true); 

    xmlHttp.onreadystatechange = function() 
    { 
     alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText); 

    if (xmlHttp.readyState==4) 
    { 
     document.getElementById("message").innerHTML=xmlHttp.responseText; 
    } 
    } 
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded") 
    xmlHttp.send(params); 

    //Testing code for synchronous mode 
    //alert("Http get status is: "+xmlHttp.status); 
    //alert("Http ready state value is: "+xmlHttp.readyState); 
    //alert("Http get response text is: "+xmlHttp.responseText); 
    //document.getElementById("message").innerHTML=xmlHttp.responseText; 
    } 


    function GetXmlHttpObject() 
    { 
     var xmlHttp=null; 
     try 
     { 
      // Firefox, Opera 8.0+, Safari 
      xmlHttp=new XMLHttpRequest(); 
     } 
     catch (e) 
     { 
      // Internet Explorer 
      try 
      { 
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
      } 
      catch (e) 
      { 
       xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
      } 
     } 
     return xmlHttp; 
    } 

    </script> 


    </head> 


    <body> 

    <form name="testform"> 
     Screename: 
     <input type="text" id="screenname1" name="screenname"> 
     <br/> 
     Score: 
     <input type="text" id="score1" name="score" onchange="recordScore(this.value)"> 
     <br/> 
     <p id="message">test</p> 

     <input type="submit" value="Submit"> 
    </form> 

    </body> 


    </html> 

回答

6

你在的onreadystatechange函數的錯誤:

alert("entered call back function. readstate value is: "+xmlHttpreadyState+". Response Text is: "+xmlHttp.responseText); 

xmlHttpreadyState應該xmlHttp.readyState

後,我固定的,它在FF3

+0

謝謝。有效。儘管多次查看代碼,但我不能相信我錯過了它。 – Satish 2008-12-31 16:40:36

0

糾正我,如果我錯了,但對於POST你不需要像這樣的Content-Length做一個setRequestHeader;

xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xmlHttp.setRequestHeader('Content-length',(params?params.length:0)); 
xmlHttp.send(params); 

這可能會改正您的問題。

+0

工作對我來說它的工作不會增加該行。我會進一步研究你的觀點。我非常感謝你的幫助。 RoBorg的答案解決了我的問題 – Satish 2008-12-31 16:44:26