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

时间:2014-04-08 01:04:19

标签: javascript ajax xmlhttprequest

如何检测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。

谢谢!

5 个答案:

答案 0 :(得分:6)

您可以检查http状态是500还是500,这意味着请求http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error

中发生了错误
 if (xmlhttp.status >= 500){
    alert('error');
 }

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

答案 1 :(得分:2)

应该使用

onerror回调来处理错误,如下所示:

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

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

答案 2 :(得分:1)

我所做的是使用一个名为'boomerang'的全局变量(我知道很诙谐)

所以当你发出请求时,make boomerang = 1然后成功make boomerang = 0

然后在您发出请求后的某个适当时间,您可以检查boomerang = 1或= 0

答案 3 :(得分:1)

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

这是一个代码列表:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

答案 4 :(得分:0)

你不会需要更多。除了评论之外,在else子句中做一些事情。

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