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

标签 javascript php ajax

我的代码应该只在通过 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/

相关文章:

php - Laravel 5 在 POST 状态 302 找到

javascript - 如何将输入框(<表单名称="form1">)的值回显到输入框(<表单名称="form2">)

javascript - 使用 vue 组件时避免直接修改 prop

php - Zend 框架 2 : Understanding plugins & services

php - 处理对象中的复杂结果——异常?

xml - Ajax:定义与实现? (XML 与 JSON 与其他)

javascript - IE9 关联数组

php - jquery 循环不适用于 php 数据

javascript - 当我点击主菜单时,子菜单应该在 php 中突出显示

php - jquery ajax 很慢