Detect if Ajax Request had failed in JavaScript

懵懂的女人 提交于 2020-01-02 03:37:09

问题


How can I detect whether an Ajax request failed to load a file.

Here is my code for reference:

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();

Please, no jQuery.

Thanks!


回答1:


you can check if the http status is 500 or more than 500 which means an error occurred in the request http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#5xx_Server_Error

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

NOTE: you can also consider other http status numbers as you like




回答2:


onerror callback should be used for handling error, like this:

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

As far as I know, jQuery library also uses this method. Not sure which all browsers support this, but this surely works in firefox.




回答3:


What I do is use a global variable I name 'boomerang' (witty I know)

so when you send the request out make boomerang=1 and then on its success make boomerang=0

then at some appropriate time after you send the request out then you can just check if boomerang =1 or =0




回答4:


you need to check the status code- 4xx and 5xx codes are errors.

here's a list of codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html




回答5:


You won't need much more. Do something in the else clause other than the comment.

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


来源:https://stackoverflow.com/questions/22925803/detect-if-ajax-request-had-failed-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!