使用JSONP在jQuery getJSON请求上获取jqXhr.responseText [英] Get the jqXhr.responseText on a jQuery getJSON request using JSONP

查看:385
本文介绍了使用JSONP在jQuery getJSON请求上获取jqXhr.responseText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个诊断站点来测试我们的服务器方法.
我想看的一件事是HTTP状态代码,并返回了实际的有效负载.

当我使用$ .ajax发出CORS请求时,可以看到jqXhr.responseText来查看有效负载,但是当我使用$ .getJSON进行JSONP请求时,jqXhr.responseText是未定义的.

将$ .getJSON与jsonp结合使用时,有什么方法可以查看HTTP有效负载吗?

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

推荐答案

由于弃用,我建议使用.done而不是.success.

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

.success回调(或.done)中,有三个参数:解析的响应文本,状态文本和xhr对象.

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

这是一个小提琴,您可以在其中看到完整的参数console.log.

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

http://jsfiddle.net/SDUEj/

这篇关于使用JSONP在jQuery getJSON请求上获取jqXhr.responseText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆