Skip to content Skip to sidebar Skip to footer

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. I've tried, using jQuery and JS:

Solution 1:

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). Pass a reference to that function to your async function (get_json). When the async operation is complete, call your callback function with the data you received.

Post a Comment for "Read Json File As Javascript Variable On Page Load"