检测Ajax请求是否在JavaScript中失败 [英] Detect if Ajax Request had failed in JavaScript
本文介绍了检测Ajax请求是否在JavaScript中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何检测Ajax请求是否无法加载文件.
How can I detect whether an Ajax request failed to load a file.
这是我的代码供参考:
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.
Please, no jQuery.
谢谢!
推荐答案
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');
}
注意:您还可以根据需要考虑其他http状态编号
NOTE: you can also consider other http status numbers as you like
这篇关于检测Ajax请求是否在JavaScript中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文