我的代码应该只在通过 AJAX 从服务器接收到请求时触发一次,但它似乎触发了大约 4 次。
谁能解释为什么会发生这种情况以及如何预防它? 我已经在 Chrome 和 IE 上测试过这个
index.html
<html>
<head>
<title>AJAX Test</title>
</head>
<body>
<div id="divOne">
Test
</div>
</body>
<script src="client.js"></script>
</html>
client.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();
server.php
<?php
$q = $_REQUEST["q"];
echo 'ok';
?>
最佳答案
每次状态发生变化时都会触发 onreadystatechange 事件,如您所见,有 5 种状态 here
您可能想要这样的东西:
if (xmlhttpSend.readyState==4 && xmlhttpSend.status==200){ ...}
关于javascript - AJAX 请求触发 4 次而不是一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732363/