我正在使用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');
        }
    },
});

Update:

@GeorgeCummins mentioned that it "seemed odd" to work with the response body. This is the first time that I've attempted doing this sort of thing. Is my approach not a best-practice? What would you recommend? I created another StackOverflow question for this here: What response/status code should I send to an AJAX request when there is a user/form validation error?

推荐答案

如果您使用的是jQuery1.5,那么statusCode就可以了.

If you're using jQuery 1.4, try this:

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

您应该会看到第一个alert 中的状态代码.

Jquery相关问答推荐

将搜索面板和服务器端与POST AJAX请求一起使用时出现DataTables错误

当我使用 OwlCarousel 时,没有任何显示

多个 AJAX 调用;获取所有失败的呼叫

jQuery:如何动态检测窗口宽度?

ajax调用后Jquery事件不会触发

使用 JSONP 时如何捕获 jQuery $.getJSON(或数据类型设置为jsonp的 $.ajax)错误?

jQuery UI 自动完成宽度未正确设置

使用 JQuery 更改 :before css Select 器的宽度属性

使用 JavaScript 和 jQuery,跨浏览器处理按键事件 (F1-F12)

使用 jQuery DataTables 时禁用最后一列的排序

JQuery html() 与 innerHTML

Jquery .show() 不显示隐藏可见性的 div

如何将文本从 div 复制到剪贴板

我如何知道 jQuery 是否有待处理的 Ajax 请求?

超时 jQuery 效果

如何在按键事件后获取 jQuery .val()?

jQuery DataTables:控制表格宽度

jQuery select2 获取 Select 标签的值?

获取jQuery中下拉列表的值

HTMLCollection、NodeLists 和对象数组之间的区别