如何处理$ .get()中的错误

我有一个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/

对所有ajax调用使用$ .ajaxSetup是全局的。 因为$ .get函数没有任何错误回调,所以在$ .ajaxSetup中定义error handling程序是处理错误的唯一方法。 如果使用$ .ajax,则可以像这样在$ .ajax调用中定义error handling程序

 $.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调用,这样您就可以获得更具体的错误消息。 但是使用全局error handling程序也同样有用。

你可以在$(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); } 

从http://api.jquery.com/jQuery.ajax/复制/粘贴:

statusCode(已添加1.5){}
当响应具有相应代码时要调用的数字HTTP代码和函数的映射。 例如,以下将在响应状态为404时发出警报:

 $.ajax({ statusCode: {404: function() { alert('page not found'); } }); 

如果请求成功,则状态码函数采用与成功回调相同的参数; 如果它导致错误,它们采用与错误回调相同的参数。

从jQuery 1.5开始,所有jQuery的Ajax方法都返回XMLHTTPRequest对象的超集。 $ .get()返回的这个jQuery XHR对象或“jqXHR”实现了Promise接口,为它提供了Promise的所有属性,方法和行为。

 var jqxhr = $.get( "example.php", function() { alert( "success" ); }) .done(function() { alert( "second success" ); }) .fail(function() { alert( "error" ); }) .always(function() { alert( "finished" ); });