检测 Ajax 请求在 JavaScript 中是否失败

Detect if Ajax Request had failed in JavaScript

本文关键字:是否 失败 JavaScript Ajax 请求 检测      更新时间:2023-09-26

如何检测 Ajax 请求是否加载文件失败。

这是我的代码供参考

var pro = undefined;
var xmlhttp;
if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
}
else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        pro = JSON.parse(xmlhttp.responseText);
    }
}
xmlhttp.open("GET","data.json",true);
xmlhttp.send();

拜托,没有jQuery。

谢谢!

您可以检查HTTP状态是500还是大于500,这意味着请求 http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error 中发生了错误

 if (xmlhttp.status >= 500){
    alert('error');
 }

注意:您还可以根据需要考虑其他http状态号码

onerror回调应该用于处理错误,如下所示:

xmlhttp.onerror = function onError(e) {
    alert("Error " + e.target.status + " occurred while receiving the document.");
}

据我所知,jQuery库也使用这种方法。不确定哪些浏览器都支持此功能,但这肯定适用于 Firefox。

我所做的是使用一个全局变量,我命名为"回旋镖"(我知道很机智)

因此,当您发送请求时,使回旋镖= 1,然后在成功时使回旋镖= 0

然后在发送请求后的某个适当时间,您可以检查回旋镖是 =1 还是 =0

您需要检查状态代码 - 4xx 和 5xx 代码是错误。

以下是代码列表: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

你不需要更多。在 else 子句中执行注释以外的操作。

xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        pro = JSON.parse(xmlhttp.responseText);
    } else {
        if (xmlhttp.readyState==4) {
            // Something failed
        }
    }
}