简体   繁体   English

在页面加载时将 json 文件读取为 javascript 变量

[英]Read json file as javascript variable on page load

I'm trying to read data from a json file into JavaScript so it can be used by other functions that are called when a user interacts with the page.我正在尝试将 json 文件中的数据读取到 JavaScript 中,以便用户与页面交互时调用的其他函数可以使用它。 I've tried, using jQuery and JS:我已经尝试过,使用 jQuery 和 JS:

var products = null;
$.getJSON("products.json", function(data) {
  products = data;
  console.log(data);
});
console.log(products);

Which produces, as expected:正如预期的那样产生:

null
Array [ {…}, {…} ]

I understand this is because of the asynchronous nature of the jQuery code execution.我知道这是因为 jQuery 代码执行的异步特性。 I've read into it a bit, but I'm just struggling to wrap my head around how to re-structure my code (coming from pretty much exclusively Python).我已经阅读了一些内容,但我只是在努力思考如何重新构建我的代码(几乎完全来自 Python)。

This is how I'm seeing it:这就是我的看法:

var products = null;
$.getJSON("products.json", function(data) {
  products = data;
  console.log(data);
});

function do_stuff(){
  // Access the attributes of data and do stuff
}

function do_more_stuff(){
  // Do some more stuff with the data
}

I would probably have do_stuff() execute when the page body loads, and let's say do_more_stuff executes when the user selects something in a dropdown menu.我可能会在页面正文加载时执行do_stuff() ,假设当用户在下拉菜单中选择某些内容时执行do_more_stuff Both need to access the data in products.json.两者都需要访问 products.json 中的数据。 I know there are many examples out there, but I'm just not getting it.我知道那里有很多例子,但我就是不明白。 How can I re-structure the code to actually work?如何重新构建代码以使其实际工作?

I believe you are looking for something like this:我相信你正在寻找这样的东西:

function get_json(cb) {
    $.getJSON("products.json", function(data) {
      cb(data);
    });  
}

function cb(data) {
    // do stuff here if you want
    console.log(data)
}

get_json(cb)

Create a callback function cb (or call it do_stuff if you'd like).创建一个回调 function cb (如果你愿意,也可以称之为 do_stuff )。 Pass a reference to that function to your async function (get_json).将对该 function 的引用传递给您的异步 function (get_json)。 When the async operation is complete, call your callback function with the data you received.异步操作完成后,使用您收到的数据调用您的回调 function。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM