如何处理异步getJSON来复制json对象?

时间:2013-04-08 22:27:32

标签: javascript json

如何分配/克隆收到的JSON对象以前定义JavaScript对象booksJSON?我需要让所有功能都可以访问booksJSON

var booksJSON = {};
    function getBooks(){
    $.getJSON( "bookstore.json", function( json ) {

        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON  =  json;  // CLONE OBJECTS 
   });
}

更新:

新代码:

    var booksJSON = {};
function getBooks(){
    return $.getJSON( "bookstore.json" );
}


$(document).ready(function(){

     getBooks();
     getBooks().done(function(json) {
        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON = json;
        alert(JSON.stringify(booksJSON));
    });

});

1 个答案:

答案 0 :(得分:3)

它与克隆无关! $.getJSON 异步$.getJSON函数完成后,您无法使用数据,这就是成功回调所针对的数据。

var booksJSON = {};
function getBooks(){
    $.getJSON( "bookstore.json", function( json ) {

        /* This is an async function, it executes at a later time */

        $.each(json.books, function(i, json){
            renderEntity(json);
        });
        booksJSON  =  json;  // here json is available
   });
   console.log( booksJSON ); // this happens before the above function, 
                             // so here booksJSON is still an empty object, 
                             // as nothing has been added yet
}

你唯一能做的就是:

function getBooks(){
    return $.getJSON( "bookstore.json" );
}

getBooks().done(function(json) {
    $.each(json.books, function(i, json){
        renderEntity(json);
    });
});

如果有帮助吗?