开发者

jQuery ajax with non 200 responses

开发者 https://www.devze.com 2023-03-02 23:53 出处:网络
How do I make success* fire for all 开发者_Python百科status codes? $.ajax({ url: \"/\" , dataType: \'json\'

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

精彩评论

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