AJAX 请求触发 4 次而不是一次


AJAX request firing 4 times instead of once

我的代码应该只在通过 AJAX 收到来自服务器的请求时触发一次,但它似乎触发了大约 4 次。

谁能解释为什么会发生这种情况以及如何防止它?我已经在Chrome和IE上对此进行了测试

索引.html

<html>
    <head>
        <title>AJAX Test</title>
    </head>
    <body>
        <div id="divOne">
            Test
        </div>
    </body>
    <script src="client.js"></script>
</html>

客户端.js

var xmlhttpSend;
xmlhttpSend = new XMLHttpRequest();
xmlhttpSend.onreadystatechange=function(){
    //The code in this area should only fire once on receiving a response
    //from the server (but it seems to run 4 times)
    var getText = xmlhttpSend.responseText;
    document.getElementById('divOne').innerHTML = getText;
    alert(getText);
}
xmlhttpSend.open("POST", "server.php?q="+encodeURIComponent("test"), true);
xmlhttpSend.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttpSend.send();

服务器.php

<?php
    $q = $_REQUEST["q"];
    echo 'ok';
?>

每次状态更改时都会触发事件 onreadystatechange,如下所示有 5 种状态

你可能想要这样的东西:

if (xmlhttpSend.readyState==4 && xmlhttpSend.status==200){ ...}

根据这篇 w3schools 文章,这听起来是正确的行为,因为在请求周期中,readyState将以 1 为增量从 0 更改为 4。