【问题标题】:jQuery AJAX Error Handling (HTTP Status Codes)jQuery AJAX 错误处理(HTTP 状态码)
【发布时间】:2012-09-25 22:17:29
【问题描述】:

我们有一个 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() 调用中的两个位置进行相同错误处理更好的范例?它不是很干,我敢肯定我只是在这些情况下错过了一些关于良好错误处理实践的东西。

【问题讨论】:

  • 我假设 HTTP 状态代码,您的意思是您在出错时将 501 作为 HTTP 状态代码发回。如果您在服务器端正确处理错误,为什么要这样做?
  • 查看 jquery.ajax (api.jquery.com/jQuery.ajax) statusCode 参数。
  • @LawrenceJohnson:我正在使用响应代码,因为它们本来就是要使用的。发送 200 OK 每个响应都需要重新发明关于错误代码/消息的轮子。
  • 是的,但是这些错误在网络级别的协议中。如果您认为验证错误与 Http 错误相同,那您就大错特错了。
  • @Liam:我的问题与如何从 jQuery.ajax() 中获取响应代码无关。

标签: jquery ajax error-handling


【解决方案1】:

查看jQuery.ajaxError()

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-05
    • 2020-07-14
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2011-12-02
    相关资源
    最近更新 更多