相关疑难解决方法(0)

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

我们有一个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()通话中的两个位置进行相同的错误处理?它不是很干,而且我确信在这些情况下,我错过了一些关于良好错误处理方法的内容.

ajax error-handling jquery

30
推荐指数
1
解决办法
8万
查看次数

标签 统计

ajax ×1

error-handling ×1

jquery ×1