我正在使用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');
}
},
});
Run Code Online (Sandbox Code Playgroud)
@GeorgeCummins提到与响应机构合作"似乎很奇怪".这是我第一次尝试做这类事情.我的方法不是最佳做法吗?你会推荐什么?我在这里为此创建了另一个StackOverflow问题:当存在用户/表单验证错误时,我应该向AJAX请求发送什么响应/状态代码?
Ale*_*lds 89
如果你使用的是jQuery 1.5,那么statusCode就行了.
如果你正在使用jQuery 1.4,试试这个:
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
Run Code Online (Sandbox Code Playgroud)
您应该从第一个警报中看到状态代码.
Geo*_*ins 57
您应该使用以下statusCode设置创建操作地图:
$.ajax({
statusCode: {
400: function() {
alert('400 status code! user error');
},
500: function() {
alert('500 status code! server error');
}
}
});
Run Code Online (Sandbox Code Playgroud)
参考(滚动到:'statusCode')
编辑(回应评论)
如果你需要根据响应体中返回的数据采取行动(这对我来说似乎很奇怪),你需要使用error:而不是statusCode:
error:function (xhr, ajaxOptions, thrownError){
switch (xhr.status) {
case 404:
// Take action, referencing xhr.responseText as needed.
}
}
Run Code Online (Sandbox Code Playgroud)
使用
statusCode: {
404: function() {
alert('page not found');
}
}
Run Code Online (Sandbox Code Playgroud)
-
$.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');
}
}
});
Run Code Online (Sandbox Code Playgroud)
另一种解决方案是使用response.status函数。这将为您提供由ajax调用返回的http状态。
function checkHttpStatus(url) {
$.ajax({
type: "GET",
data: {},
url: url,
error: function(response) {
alert(url + " returns a " + response.status);
}, success() {
alert(url + " Good link");
}
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
139455 次 |
| 最近记录: |