onreadystatechange函数未被调用

时间:2008-12-31 15:08:15

标签: javascript html ajax

由于某种原因,在异步模式下不会调用onreadystatechange回调函数。我在同步模式下测试了帖子,并确认帖子本身工作正常(注释掉我用来检查同步模式下的帖子的测试代码)。在safari和firefox最新版本中都会出现此问题。有人可以告诉我这里我做错了什么吗?谢谢。

    <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>

2 个答案:

答案 0 :(得分:6)

你在onreadystatechange函数中有错误:

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

xmlHttpreadyState应为xmlHttp.readyState

在我解决之后,它在FF3中适用于我

答案 1 :(得分:0)

如果我错了,请纠正我,但对于POST,你不需要为内容长度做一个setRequestHeader,如此;

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

这可能会纠正您的问题。