页面准备就绪时,将数据从本地文件存储到变量

页面准备就绪时,将数据从本地文件存储到变量

问题描述:

var persons;
        $(function () {
            $.getJSON("person.json", function(data){ persons = JSON.stringify(data); 
                console.log("This is inside: "+ persons); });
                console.log("This is outside" + persons);
            }
            getJSONData();
        });





i想要将本地文件(person.json)中的数据存储到开头的变量中。但结果是:



i want to get and store data from local file(person.json) into a variable at the beginning. But the result is:

This is outside: undefined
This is inside: [{"name":"user1","gender":"male"},{"name":"user2"},{"gender":"female"}]





我怎么能在一开始就将数据存储到变量中?



我尝试过:





So how can i get and store data into variable at the very beginning?

What I have tried:

var persons;
    function getJSONData() {
        $.getJSON("person.json", function(data){ persons = JSON.stringify(data); 
        console.log("This is inside: "+ persons); });
    }
    getJSONData();
    $(function () {
        console.log("This is outside: " + persons);
    });



我试过这个,但结果是一样的......


I have tried this, but the result is same...

function (){


.getJSON( person.json function (data){persons = JSON .stringify(data);
console .log( 这里面是: +人);});
console .log( 这是 +人)之外;
}
getJSONData();
});
.getJSON("person.json", function(data){ persons = JSON.stringify(data); console.log("This is inside: "+ persons); }); console.log("This is outside" + persons); } getJSONData(); });





i想要将本地文件(person.json)中的数据存储到变量中。但结果是:



i want to get and store data from local file(person.json) into a variable at the beginning. But the result is:

This is outside: undefined
This is inside: [{"name":"user1","gender":"male"},{"name":"user2"},{"gender":"female"}]





我怎么能在一开始就将数据存储到变量中?



我尝试过:





So how can i get and store data into variable at the very beginning?

What I have tried:

var persons;
    function getJSONData() {


.getJSON( person.json function (data){persons = JSON .stringify(data);
console .log( 这里面是: + persons);});
}
getJSONData();
.getJSON("person.json", function(data){ persons = JSON.stringify(data); console.log("This is inside: "+ persons); }); } getJSONData();