我有这段代码:
var my = {};
(function () {
var self = this;
this.sampleData = { };
this.loadData = function() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
}
);
};
}).apply(my);
my.loadData();
console.log(my.sampleData); // {}
问题是my.sampleData没有任何内容。
在此处试用此示例:http://jsfiddle.net/r57ML/
答案 0 :(得分:3)
原因是getJSON
调用异步,因此您需要在返回之前查找数据。相反,直接或间接地使用数据在回调中放置代码。
例如,您可以让loadData
来电接受回电:
var my = {};
(function () {
var self = this;
this.sampleData = { };
this.loadData = function(callback) {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
callback(); // <==== Call the callback
}
);
};
}).apply(my);
my.loadData(function() { // <=== Pass in a callback
console.log(my.sampleData); // Now the data is htere
});
旁注:由于您的my
对象是单身,因此您可以简化该代码,不需要apply
,this
或self
,因为您的匿名函数是对定义my
的上下文的闭包:
var my = {};
(function () {
my.sampleData = { };
my.loadData = function(callback) {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
my.sampleData = data;
callback();
}
);
};
})();
my.loadData(function() {
console.log(my.sampleData); // Now the data is htere
});
当然,如果您正在使用构造函数或其他东西(您不在引用的代码中,但是......),那么当然您可能需要更复杂的结构。
答案 1 :(得分:0)
(function () {
var self = this;
this.sampleData = {};
this.loadData = function() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?',
{tags: "cat", tagmode: "any", format: "json"},
function(data){
self.sampleData = data;
console.log(my.sampleData); // you get sample data after ajax response
},
'json');
};
}).apply(my);
my.loadData();