jquery how to check response type for ajax call

后端 未结 5 734
孤街浪徒
孤街浪徒 2020-12-04 13:57

How can I determine the response type of ajax call in Jquery? At times, the server sends json response and at times it sends only the html for display purposes. Right now I

5条回答
  •  佛祖请我去吃肉
    2020-12-04 14:41

    If the response is parsed as JSON, the jqXHR object will have a responseJSON property.

    $.ajax(
        // ...
    ).done(function(data, textStatus, jqXHR) {
        if (jqXHR.responseJSON) {
            // handle JSON
        } else {
            // handle html
        }
    }).fail(function(jqXHR, textStatus, errorThrown) {
        if (jqXHR.responseJSON) {
            // handle JSON
        else {
            // handle html
        }
    })
    

    From the jQuery.ajax documentation:

    If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

提交回复
热议问题