Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
jQuery AJAX错误处理(HTTP状态代码)_Jquery_Ajax_Error Handling - Fatal编程技术网

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

jQuery AJAX错误处理(HTTP状态代码),jquery,ajax,error-handling,Jquery,Ajax,Error Handling,我们有一个API,它使用正确的HTTP状态代码来处理错误,并用JSON编码的响应和适当的内容类型头进行响应。我的情况是,jQuery.ajax()在遇到HTTP错误状态时触发错误回调,而不是成功回调,因此,即使我们有一个可理解的JSON响应,我们也必须采取以下措施: $.ajax({ // ... success: function(response) { if (response.success) { console.log('Succe

我们有一个API,它使用正确的HTTP状态代码来处理错误,并用JSON编码的响应和适当的
内容类型
头进行响应。我的情况是,
jQuery.ajax()
在遇到HTTP错误状态时触发
错误
回调,而不是
成功
回调,因此,即使我们有一个可理解的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()
调用中,有比在两个位置执行相同的错误处理更好的范例吗?它不是很干燥,我确信我在这些情况下错过了一些关于良好错误处理实践的内容。

请查看

它捕获全局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
});

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