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

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

问题描述

我们有一个API,它使用适当的HTTP状态codeS中的错误,并回应JSON-CN codeD的反应和相应的内容类型头。我的情况是, jQuery.ajax()触发错误遇到一个HTTP错误状态时,的回调,而不是成功回调,所以即使我们有一个理解的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状态codeS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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