以下是get.json的内容:
{“id”:1,“name”:“hello”}
和脚本/标记:
var entries = [];
function Data(){}
Data.prototype.get = function(id){
var object = {}, length = entries.length, success = false;
for (var i = 0; i < length; i++) {
if (entries[i].id == id) {
object = entries[i];
i = length;
console.log("From browser: " + object.name);
success = true;
}
}
if (!success) {
$.getJSON("get.json", function(data){
entries.push(data);
object = data;
console.log("Newly fetched: " + object.name);
});
}
return object;
}
$(function(){
var data = new Data();
data.get(1);
console.log((data.get(1).name);
});
答案 0 :(得分:1)
我会使用回调。如果数据存在于浏览器缓存中,则将立即触发回调。如果没有,它将在异步请求完成时被触发。
function Data(){}
Data.prototype.get = function(id, callback){
var object = {}, length = entries.length, false;
for (var i = 0; i < length; i++) {
if (entries[i].id == id) {
object = entries[i];
console.log("From browser: " + object.name);
callback(object);
return; // Don't let execution continue
}
}
$.getJSON("get.json", function(data){
entries.push(data);
object = data;
console.log("Newly fetched: " + object.name);
callback(object);
});
}
$(function(){
var data = new Data();
data.get(1, function(obj){
console.log(obj.name);
});
});
另一种方法是让你的AJAX调用同步,暂停所有执行,但这是一个非常坏主意。
编辑:我还稍微更改了代码以移除success
变量,并选择从for
循环返回(从而打破循环)。< / p>