我有一个jquery代码,其中我使用get()和调用一些远程url /文件.
现在我想知道最好的方法来处理这个错误.
现在我想知道最好的方法来处理这个错误.
我在做什么是:
$(document).ready(function() {
$.ajaxSetup({
error: function(x,e) {
if (x.status == 0) {
alert(' Check Your Network.');
}
else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else {
alert('UnkNow Error.\n' + x.responseText);
}
}
});
$.get("HTMLPage.htm",function(data) {
alert(data);
$('#mydiv').html(data);
});
});
这是很好的工作.但想知道有没有更好的方式这样做?
编号:http://www.maheshchari.com/jquery-ajax-error-handling/
解决方法
使用$.ajaxSetup是所有ajax调用的全局.因为$.get函数没有任何错误回调,在$.ajaxSetup中定义错误处理程序是处理错误的唯一方法.如果你使用$.ajax,可以这样定义$.ajax调用中的错误处理程序
$.ajax({
url: "HTMLPage.htm",success: function(data) {
alert(data);
$('#mydiv').html(data);
},error: function(XMLHttpRequest,textStatus,errorThrown) {
if (XMLHttpRequest.status == 0) {
alert(' Check Your Network.');
} else if (XMLHttpRequest.status == 404) {
alert('Requested URL not found.');
} else if (XMLHttpRequest.status == 500) {
alert('Internel Server Error.');
} else {
alert('UnkNow Error.\n' + XMLHttpRequest.responseText);
}
}
});
这只是特定于这个ajax调用,这样你可以有更具体的错误消息.但是使用全局错误处理程序也是一样.
您可以在$(document).ready()之外定义您的函数
$(document).ready(function() {
$.ajaxSetup({
error: AjaxError
});
$.get("HTMLPage.htm",GetSuccess);
});
function AjaxError(x,e) {
if (x.status == 0) {
alert(' Check Your Network.');
} else if (x.status == 404) {
alert('Requested URL not found.');
} else if (x.status == 500) {
alert('Internel Server Error.');
} else {
alert('UnkNow Error.\n' + x.responseText);
}
}
function GetSuccess(data) {
alert(data);
$('#mydiv').html(data);
}