Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ideal way to find out if response is JSON during ajaxSuccess

In my $.ajaxSucess() function I need to find out if the response is json. Currently I am doing this:

$('body').ajaxSuccess(function(evt, xhr, settings) {
    var contType = xhr.getAllResponseHeaders().match(/Content-Type: *([^)]+);/);
    if(contType && contType.length == 2 && contType[1].toLowerCase() == 'application/json'){    
...

Is there a better way?

like image 810
mkoryak Avatar asked Oct 05 '11 14:10

mkoryak


People also ask

What does getJSON return?

getJSON( url, [data], [callback] ) method loads JSON data from the server using a GET HTTP request. The method returns XMLHttpRequest object.

What is response data in Ajax?

Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object.


1 Answers

Assuming that you are expecting json, I'd simply try and parse it like json and catch any errors. Also see jQuery.parseJSON.

try {
    jQuery.parseJSON(response);
} catch(error) {
    // its not json
}

If you are expecting one of a number of different response types (i.e. it might be json or it might just be text, etc) then you might need to get more complicated. I'd use xhr.getResponseHeader("content-type"). See this blog post for some great detail on handling content types.

$.ajax({
    type: "POST",
    url: "/widgets", 
    data: widgetForm.serialize(), 
    success: function(response, status, xhr){ 
        var ct = xhr.getResponseHeader("content-type") || "";

        if (ct.indexOf(‘html’) > -1) {
            widgetForm.replaceWith(response);
        }

        if (ct.indexOf(‘json’) > -1) {
            // handle json here
        } 
    }
});
like image 124
jtfairbank Avatar answered Sep 19 '22 19:09

jtfairbank