我正在尝试将 JSON 文件读入全局对象数组。该代码有效,但我似乎无法找到将数据从 Ajax $.getJSON 调用中获取到全局变量中的方法。也许这是因为范围和/或同步。
我尝试了几种方法,并且正在使用以下代码读取 JSON 文件(请参阅Using Jquery to get JSON objects from local file):
var questions = {};
$(document).ready(function() {
readJsonFile().done(function (questions) {
// This outputs the array of objects (questions) OK ->
console.log("Questions read from JSON file: " + questions);
});
// Cannot read from the array here
console.log("Question 1: " + questions[0].question);
...
function readJsonFile() {
return $.getJSON("questions.json").then(function (data) {
// This was in the original post and didn't seem to return the array
// return data.items;
return data;
});
};