gpt4 book ai didi

javascript - Ajax 发送功能不会触发?

转载 作者:行者123 更新时间:2023-11-28 02:57:57 25 4
gpt4 key购买 nike

每当我运行这个文件时,代码都会运行到发送函数触发的位置,然后只有当我在它后面直接有一个警报函数时,如果我取出警报(“已发送”);它才会触发。然后它回复 ServerReadyyState is:1。

可能是什么问题?请有人帮忙,我已经在本地计算机和个人服务器上尝试过,并得到了相同的结果。非常感谢任何帮助。

代码:

/**
* @author d
*/
var xhr;

function getPlants(xhr) {
try {
xhr = new XMLHttpRequest();
} catch (microsoft) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
xhr = false;
alert("ajax not supported");
}
}
}
xhr.open("GET", "db_interactions.php", true);


xhr.send(null);
alert("sent"); //the send function only works if this alert functions is here
if (xhr.readyState == 4) {

return xhr.responseText;
} else {
alert("Server ReadyState is:" + xhr.readyState);
xhr.abort();
//getPlants(xhr);
}
}

最佳答案

AJAX 是异步的。您不能立即检查就绪状态。

正确的设计模式是为 AJAX 调用分配一个函数,以便在就绪状态更改时运行。

xhr.onreadystatechange = function () { alert('It changed!') }

that 函数中,您需要检查状态是否为 4。如果是,您就可以处理输出了。如果不是,则不执行任何操作,因为在就绪状态为 4 之前该函数将被调用几次。

关于javascript - Ajax 发送功能不会触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2102146/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com