我使用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问题:What response/status code should I send to an AJAX request when there is a user/form validation error?
解决方法
如果你使用jQuery 1.5,那么statusCode将工作。
如果你使用jQuery 1.4,试试这个:
- error: function(jqXHR,textStatus,errorThrown) {
- alert(jqXHR.status);
- alert(textStatus);
- alert(errorThrown);
- }
您应该从第一个警报中看到状态代码。