Get the jqXhr.responseText on a jQuery getJSON request using JSONP

csauve picture csauve · Mar 30, 2012 · Viewed 14.3k times · Source

I am writing a diagnostic site to test our server methods.
One of the things I would like to see is the HTTP status code, and the actual payload returned.

When I make a CORS request by using $.ajax, I can see the jqXhr.responseText to see the payload, but when I use $.getJSON to make a JSONP request, jqXhr.responseText is undefined.

Is there any way to see the HTTP payload when using $.getJSON with jsonp?

function callJavascript(url, callback) {
    var closedData;
    var jqXhr = $.getJSON(url, function (data) {
        closedData = data;
    })
    .success(function() {
        $('#statusCode').text(jqXhr.status); //200
        $('#statusText').text(jqXhr.statusText); //success
        //this is undefined
        $('#responseText').text(jqXhr.responseText); 
        callback(closedData);
    });
};


function someCall()
{
    var callback = function(data) {
        //snip... will pop UI with json object returned
    };
    callJavascript('http://myurl?callback=?', callback);
};

Answer

Kevin B picture Kevin B · Mar 30, 2012

I suggest using .done instead of .success due to deprecation.

Within the .success callback (or .done) there are three parameters: parsed response text, status text, and xhr object.

function callJavascript(url, callback) {
    var closedData;
    $.getJSON(url, function (data) {
        closedData = data;
    })
    .done(function(parsedResponse,statusText,jqXhr) {
        $('#statusCode').text(jqXhr.status); //200
        $('#statusText').text(jqXhr.statusText); //success
        //this should not be undefined
        $('#responseText').text(jqXhr.responseText); 
        console.log(parsedResponse);
        callback(closedData);
    });
};

Here's a fiddle where you can see the full console.log of the arguments.

http://jsfiddle.net/SDUEj/