多次Ajax调用有时会失败

Multiple Ajax calls sometimes fail

本文关键字:失败 Ajax 调用 多次      更新时间:2023-09-26

我有一个PHP脚本,查询数据库并返回一个表,取决于输入,例如results. PHP ?f=1.

我试图从JavaScript调用它多次:

function go(n,divid) {
 document.getElementById(divid).innerHTML = "<img src='"load.gif'">";
 var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById(divid).innerHTML = xmlhttp.responseText;
    }
 }
 xmlhttp.open("GET", n, true);
 xmlhttp.send();
}

调用后

    go('results.php?print=1&nh=1','d1');
    go('results.php?print=2&nh=1','d2');
    go('results.php?print=3&nh=1','d3');
    go('results.php?print=4&nh=1','d4');

PHP代码连接到SQLite3数据库。上面的问题是,有时它可以工作,但有时其中一个查询无法由SQLite3::prepare()准备。

怎么了?一个简单的竞争条件?javascript问题?当results.php只被调用一次时,查询总是成功的。

谢谢。

使用xhttp代替xmlhttp。

function go(n,divid) {
 var xhttp = new XMLHttpRequest();
 document.getElementById(divid).innerHTML = "<img src='"load.gif'">";
 xhttp.onreadystatechange = function () {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        document.getElementById(divid).innerHTML = xhttp.responseText;
    }
 }
 xhttp.open("GET", n, true);
 xhttp.send();
}
 go('results.php?print=1&nh=1','d1');