从jQuery GET传递或返回JSON对象 [英] Pass or return JSON Object from jQuery GET
问题描述
我有一个函数,该函数对嵌套的JSON对象发出GET请求.该对象已成功返回,但是您无法访问该返回对象内的其他对象.
I have a function that makes a GET request for a nested JSON object. The object is returned successfully but you can't access the other objects within the returned object.
对象看起来像这样:
{
"student": {
"hobbies": ["reading", "dancing", "music"],
"subjects": ["english", "maths", "science"]
}
}
这是函数:
var superObject = {
getData: function(obj) {
$.get(obj.target, function(callbackObject) {
// It works fine if i log callbackObject
// console.log(callbackObject);
return callbackObject;
}
},
useData: function() {
var data = superObject.getData({'target': 'file.json'});
var hobbies = data.student.hobbies;
console.log(hobbies); // This fails and returns nothing.
}
}
推荐答案
问题是您要从$ .get 回调中返回callbackObject
,而不是从getData
函数中返回. $ .get是异步,因此直到getData()
完成很长时间之后,它的回调函数才会触发.这就是为什么您看到未定义的原因.
The problem is that you're returning callbackObject
from your $.get callback, and not from your getData
function. $.get is asynchronous, so its callback will not fire until long after getData()
has finished. That's why you're seeing undefined.
那又怎么样呢?
var superObject = {
getReuslts: {},
getData: function(obj) {
$.get(obj.target, function(callbackObject) {
getReuslts = callbackObject;
this.useData();
}
},
useData: function() {
var hobbies = getReuslts.student.hobbies;
console.log(hobbies);
}
}
当然,这会在useData和getData之间创建一个时间依赖性.为什么不在函数中创建此对象,以便添加一些封装?
Of course this would create a temporal dependency between useData and getData. Why not create this object in a function so you can add some encapsulation?
funcition getSuperObject = {
var result = {};
var getReuslts = {};
function useData() {
var hobbies = getReuslts.student.hobbies;
console.log(hobbies);
}
result.getData = function(obj) {
$.get(obj.target, function(callbackObject) {
getReuslts = callbackObject;
useData();
});
};
return result;
}
或提供您自己的回调:
var superObject = {
getData: function(obj, callback) {
$.get(obj.target, function(callbackObject) {
if (callback)
callback(calbackObject);
});
}
}
然后
superObject.getData({'target': 'file.json'}, function(result) {
var hobbies = result.student.hobbies;
console.log(hobbies); // This fails and returns nothing.
});
这篇关于从jQuery GET传递或返回JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!