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

依然范特西╮ 提交于 2019-12-25 15:29:51

问题


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);
};

回答1:


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/



来源:https://stackoverflow.com/questions/9949146/get-the-jqxhr-responsetext-on-a-jquery-getjson-request-using-jsonp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!