就绪状态和状态分别等于 1 和 0


ReadyState and status equal 1 and 0 respectively

我的Linux机器上重新安装了Appache和PHP。这是我为测试事情如何工作而想出的第一个脚本:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 5//EN"
    "http://www.w3.org/TR/html5/html5.dtd"
    >
<html lang="en">
<head>
    <title>First Ajax</title>
    <script language="javascript" type="text/javascript">
    var xmlhttp;
    function getNum()
    {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = callback;
        xmlhttp.open("GET" , "random.php" , true);
        xmlhttp.send();
    }
    //When Information comes back from the server
    function callback()
    {
        if(xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert("Ready")
            document.getElementById('result').innerHTML = xmlhttp.responseText;
        }
        else
        {
            alert("Nope")
        }
    }
    </script>
</head>
<body>
    <div id="result">
    </div>
    <input type="button" value="Get Random Number" onclick="getNum()"/>
</body>
</html>

但是,似乎该行xmlhttp.readyState==4 && xmlhttp.status==200计算结果为 false,因为返回了"Nope"。如果我用||替换&&也是如此. 如果我从浏览器转到本地主机/随机.php,它可以正常工作。我知道确切的代码适用于其他计算机。知道我被困在哪里吗?

编辑:根据@Musa的评论,我意识到readyState等于1,状态等于0,这意味着对象已创建,并且尚未调用发送方法(http://msdn.microsoft.com/en-us/library/ms753800%28v=vs.85%29.aspx)。反正我还是迷路了。

readyState不会

直接转到 4,它可以在达到 4 之前转到其他值。尝试这样的事情

    if(xmlhttp.readyState==4){ 
        if (xmlhttp.status==200)
        {
            alert("Success")
            document.getElementById('result').innerHTML = xmlhttp.responseText;
        }
        else
        {
            alert("Failure")
        }
    }