对象返回需要等到JSON请求完成

时间:2009-11-23 04:34:25

标签: javascript jquery json oop object

以下是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);
        });

1 个答案:

答案 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>