-1

如何将接收到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));
    });

});
4

1 回答 1

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);
    });
});

如果这有帮助吗?

于 2013-04-08T22:30:14.090 回答