如何检查 AJAX 代码是否执行?



如何了解 ajax 代码中调用的文件是否已执行?

function get_data(radioAns) 
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200) 
{
document.getElementById("dataExchange").innerHTML =this.responseText;
}
};
xhttp.open("GET","example.php?radioAns="+radioAns, true);
xhttp.send();
}

这是我的 ajax 代码。 我想知道如何检查是否调用了示例.php文件。

您需要将readyStatestatus的检查分开。

readyState4(如果您喜欢常量,则XMLHttpRequest.DONE(表示请求已完成(成功或错误(。

[200, 300)状态通常被认为是成功的。[300, 400)通常表示某种无内容的响应(如重定向(。等于或大于400的任何值都是错误。

见 https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

考虑到所有这些,请考虑类似

xhttp.onreadystatechange = function() {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status >= 200 && this.status < 300) {
// success
}
if (this.status >= 400) {
// error
}
}
// else, the request has not completed *yet*
}

最新更新