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

Pro*_*ogo 6 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();
Run Code Online (Sandbox Code Playgroud)

拜托,没有jQuery.

谢谢!

Mp *_*ega 6

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

 if (xmlhttp.status >= 500){
    alert('error');
 }
Run Code Online (Sandbox Code Playgroud)

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