JQuery: 如何从 $. ajax.error 方法中获取 HTTP状态码?

我使用 jQuery 发出一个 AJAX 请求。无论 HTTP状态码是400错误还是500错误,我都想执行不同的操作。我怎么才能做到呢?

$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
error: function(data){
//get the status code
if (code == 400) {
alert('400 status code! user error');
}
if (code == 500) {
alert('500 status code! server error');
}
},
});

更新:

@ GeorgeCummins 提到与响应机构合作“似乎很奇怪”。这是我第一次尝试做这种事。我的方法难道不是最佳实践吗?你有什么建议吗?我在这里为此创建了另一个 StackOverflow 问题: 当出现用户/表单验证错误时,我应该向 AJAX 请求发送什么响应/状态代码?

183862 次浏览

You should create a map of actions using the statusCode setting:

$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
}
});

Reference (Scroll to: 'statusCode')

EDIT (In response to comments)

If you need to take action based on the data returned in the response body (which seems odd to me), you will need to use error: instead of statusCode:

error:function (xhr, ajaxOptions, thrownError){
switch (xhr.status) {
case 404:
// Take action, referencing xhr.responseText as needed.
}
}

use

   statusCode: {
404: function() {
alert('page not found');
}
}

-

$.ajax({
type: 'POST',
url: '/controller/action',
data: $form.serialize(),
success: function(data){
alert('horray! 200 status code!');
},
statusCode: {
404: function() {
alert('page not found');
},


400: function() {
alert('bad request');
}
}


});

If you're using jQuery 1.5, then statusCode will work.

If you're using jQuery 1.4, try this:

error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}

You should see the status code from the first alert.

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}

Here you can use this too it works for me

$.ajax({
success: function(data, textStatus, xhr) {
console.log(xhr.status);
},
complete: function(xhr, textStatus) {
console.log(xhr.status);
}
});