jQuery:如何从$ .ajax.error方法中获取HTTP状态代码? [英] jQuery: How to get the HTTP status code from within the $.ajax.error method?
本文介绍了jQuery:如何从$ .ajax.error方法中获取HTTP状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用jQuery发出AJAX请求.无论HTTP状态代码是400错误还是500错误,我都想执行不同的操作.我该如何实现?
I'm using jQuery to make an AJAX request. I want to perform different actions whether or not the HTTP status code is a 400 error or a 500 error. How can I achieve this?
$.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请求发送什么响应/状态代码?
推荐答案
如果您使用的是jQuery 1.5,则statusCode
将起作用.
If you're using jQuery 1.5, then statusCode
will work.
如果您使用的是jQuery 1.4,请尝试以下操作:
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.
这篇关于jQuery:如何从$ .ajax.error方法中获取HTTP状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文