jQuery AJAX错误处理(HTTP状态代码)

FtD*_*Xw6 30 ajax error-handling jquery

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

$.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...
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

是否有更好的范例,而不是在每次jQuery.ajax()通话中的两个位置进行相同的错误处理?它不是很干,而且我确信在这些情况下,我错过了一些关于良好错误处理方法的内容.

Ter*_*rry 42

查看 jQuery.ajaxError()

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

if (jqXHR.status == 500) {
  // Server side error
} else if (jqXHR.status == 404) {
  // Not found
} else if {
    ...
Run Code Online (Sandbox Code Playgroud)

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

function handleAjaxError(jqXHR, textStatus, errorThrown) {
    // do something
}

$.ajax({
    ...
    success: function() { ... },
    error: handleAjaxError
});
Run Code Online (Sandbox Code Playgroud)

  • 三等于?:) (10认同)