开发者

jQuery ajax with non 200 responses

How do I make success* fire for all 开发者_Python百科status codes?

$.ajax({
    url: "/"
    , dataType: 'json'
    , type: 'POST'
    success: function (data) {
        alert('all good');
    }
});

* note i don't care if its the "success" method that fires, i just want to have the response entity parsed as JSON.

My response entity for a 400 might be some JSON with the details as to why it was a bad request, is there some setting to make this work out of the box with jQuery? Or do I have to hand roll this?

Thanks


Use complete: function () { }, instead of success. In this case, the resulting data won't be parsed by jQuery, but you can do that yourself by performing $.parseJSON() on the XHR object's responseText:

$.ajax({
    url: "/"
    , dataType: 'json'
    , type: 'POST'
    complete: function (xhrObj) {
        var data = $.parseJSON(xhrObj.responseText || "");
        alert('all good');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜