[英]jQuery $.get returning full Object vs just what I need
Here is my code: 这是我的代码:
var source;
source = $.getJSON(url, function(json) {
return console.log(json);
});
The above is returning the full jQuery object vs the JSON I am requested. 以上是返回完整的jQuery对象与我请求的JSON。 The response looks something like this:
响应看起来像这样:
abort: function ( statusText ) {
always: function () {
complete: function () {
done: function () {
error: function () {
fail: function () {
getAllResponseHeaders: function () {
getResponseHeader: function ( key ) {
isRejected: function () {
isResolved: function () {
overrideMimeType: function ( type ) {
pipe: function ( fnDone, fnFail ) {
promise: function ( obj ) {
readyState: 4
responseText: "{'Hello':'World'}"
setRequestHeader: function ( name, value ) {
status: 200
statusCode: function ( map ) {
statusText: "OK"
success: function () {
then: function ( doneCallbacks, failCallbacks ) {
__proto__: Object
Anyone know what I am doing wrong? 谁知道我做错了什么? I have been dealing with this for a couple of hours now :(
我一直在处理这个问题几个小时:(
AJAX is asynchronous, source
cannot equal the JSON you are requesting, because it isn't available yet. AJAX是异步的,
source
不能与您请求的JSON相等,因为它尚不可用。 jQuery.getJSON
will return the jqXHR
object it creates to deal with the request and then runs away and retrieves the response. jQuery.getJSON
将返回它创建的jqXHR
对象来处理请求,然后运行并检索响应。
$.getJSON(url, function(json) {
// deal with response here
});
Upon the response being available ( some time later ), the callback (the function you're passing) is executed, so you can access the response in there via the first parameter (which you've called json
). 在响应可用( 稍后一段时间 )后,将执行回调(您正在传递的函数),因此您可以通过第一个参数(您称为
json
)访问响应。
You can see this by trying the following: 你可以通过尝试以下方法看到这一点:
console.log('1');
$.getJSON(url, function(json) {
console.log('2');
});
console.log('3');
You'll see that your console will read 1, 3, and then a split second later (ie the time to perform the HTTP request), 2; 您将看到您的控制台将读取1,3,然后在一瞬间读取(即执行HTTP请求的时间),2; This shows the getJSON response returning without completing, the script continuing to execute, and then the callback being invoked some time later .
这显示getJSON响应在没有完成的情况下返回,脚本继续执行,然后在一段时间后调用回调。
Try doing it like this: 尝试这样做:
var source;
source = $.get(url, function(data) {
return alert($.parseJSON(data));
});
As of jQuery 1.5, that method returns a jqXHR object (what you are seeing). 从jQuery 1.5开始,该方法返回一个jqXHR对象(你所看到的)。 See the docs here for more info.
有关详细信息,请参阅此处的文档。
You can see that the JSON you want is actually in the responseText variable. 您可以看到所需的JSON实际上在responseText变量中。 So it should be
source.responseText
. 所以它应该是
source.responseText
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.