如何检测jQuery ajax错误响应?

时间:2013-02-26 19:45:33

标签: jquery api jsonp http-status-codes

我能够检测到成功的响应,但无法检测到错误。我的代码:

$.ajax({
        url: url,
        dataType: 'jsonp',      
        success: function(data){
            $.each(data, function(a, b) { 
                if(b=="Processing post"){
                    $("#post_response").html('Your comment will be added soon...'); 
                }
                else if(b=="In moderation"){
                    $("#post_response").html('Your comment has been placed in moderation...');  
                }
            })
        },
        error: function(xhr, testStatus, error) {
            alert("error");
        }
    });

这些是我收到的回复。我可以检测到前2个响应,但我甚至无法提醒最后一个响应“错误”。

jQuery191004289518775843171_1361906819321({"Message":"Processing post","Code":202})

jQuery191006158838421090984_1361907415719({"Message":"In moderation","Code":202})

jQuery191006158838421090984_1361907415719({"Message":"Not logged in","Code":403})

你能看到我出错的地方吗?

1 个答案:

答案 0 :(得分:2)

错误回调仅用于服务器错误响应(即HTTP状态码4xx / 5xx错误)。由于您的所有三个响应都是有效的(即它们返回的HTTP状态代码为200),它们会触发成功回调。