jQuery AJAXerror handling(HTTP状态代码)

我们有一个API,它使用正确的HTTP状态代码来处理错误,并使用JSON编码的响应和适当的Content-Type标头进行响应。 我的情况是jQuery.ajax()在遇到HTTP错误状态时触发error回调,而不是success回调,所以即使我们有一个可理解的JSON响应,我们也必须求助于这样的事情:

 $.ajax({ // ... success: function(response) { if (response.success) { console.log('Success!'); console.log(response.data); } else { console.log('Failure!'); console.log(response.error); } }, error: function(xhr, status, text) { var response = $.parseJSON(xhr.responseText); console.log('Failure!'); if (response) { console.log(response.error); } else { // This would mean an invalid response from the server - maybe the site went down or whatever... } } }); 

有没有比在每个jQuery.ajax()调用中的两个位置执行相同error handling更好的范例? 它不是很干,而且我确信在这些情况下,我错过了一些关于良好error handling实践的内容。

查看jQuery.ajaxError()

它捕获全局Ajax错误,您可以通过多种方式处理它们:

 if (jqXHR.status == 500) { // Server side error } else if (jqXHR.status == 404) { // Not found } else if { ... 

或者,您可以自己创建一个全局error handling程序对象,并选择是否调用它:

 function handleAjaxError(jqXHR, textStatus, errorThrown) { // do something } $.ajax({ ... success: function() { ... }, error: handleAjaxError });