jQuery AJAX 错误处理(HTTP 状态代码) [英] jQuery AJAX Error Handling (HTTP Status Codes)

查看:31
本文介绍了jQuery AJAX 错误处理(HTTP 状态代码)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

We have an API which uses proper HTTP status codes for errors, and responds with JSON-encoded responses and appropriate Content-Type header. My situation is that jQuery.ajax() triggers the error callback when it encounters an HTTP error status, and not the success callback, so even when we have an intelligible JSON response, we have to resort to something like this:

$.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() 调用中的两个点进行相同的错误处理更好的范例?它不是很枯燥,我敢肯定我只是在这些情况下遗漏了一些关于良好错误处理实践的内容.

Is there a better paradigm than doing identical error handling in two spots in each jQuery.ajax() call? It's not very DRY, and I'm sure I've just missed something somewhere on good error handling practices in these cases.

推荐答案

查看 jQuery.ajaxError()

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

It catches global Ajax errors which you can handle in any number of ways:

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

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

Alternatively, you can create a global error handler object yourself and choose whether to call it:

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

$.ajax({
    ...
    success: function() { ... },
    error: handleAjaxError
});

这篇关于jQuery AJAX 错误处理(HTTP 状态代码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆