如何处理错误在$获得() [英] How to handle error In $.get()
问题描述
我有一个jQuery code中,我使用get()和调用一些远程URL /文件。 现在我想知道的最好办法是从该处理错误。
I have a jquery code in which I am using get() and calling some remote url/file. Now I want to know what the best way is to handle errors from this.
我在做什么是:
$(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);
});
});
这是工作fine.But想知道的是有这样做没有更好的办法?
This is working fine.But want to know is there any better way of doing this?
REF:<一href="http://www.maheshchari.com/jquery-ajax-error-handling/">http://www.maheshchari.com/jquery-ajax-error-handling/
推荐答案
使用$ .ajaxSetup是对所有Ajax调用。因为$不用彷徨功能没有任何错误回调,定义在$ .ajaxSetup错误处理程序处理错误的唯一方法。如果使用$阿贾克斯,你可以在$就调用这样定义的错误处理程序
Using $.ajaxSetup is global for all ajax calls. Because the $.get function doesn't have any error callbacks, defining an error handler in $.ajaxSetup is the only way to handle errors. If you use $.ajax, you can define the error handler in the $.ajax call like this
$.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调用,这样就可以有更多的具体错误信息。但是用全局错误处理效果一样好。
This is specific to only this ajax call, that way you can have more specific error messages. But using the global error handler works just as well.
您可以在$(文件)。就绪()这样的外部定义功能
You could define your functions outside of the $(document).ready() like this
$(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);
}
这篇关于如何处理错误在$获得()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!