简体   繁体   中英

jquery store json object from url in javascript variable

How do I use the .getJSON() function to save a json object as a javascript variable?

var js = 
$.getJSON(url, 
    function(data) {...}
);

do I need the function(data) {...} callback?

The var would look like normal json format (like a dictionary in python?)

{"query":{"count":1,"created":"2014-07-18", ...

You would need to declare the variable first and then assign the value in the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);

EDIT:

If your code looks something like the following, then it probably won't work:

var js;
$.getJSON(url, 
    function(data) {
        js = data;
        // or use your data here by calling yourFunction(data);
    }
);
$("div").html(js);

That's because the $.getJSON() is an asynchronous function. That means the code underneath will continue executing without waiting for the $.getJSON to finish. Instead you would want to use the variable inside the success function as such:

var js;
$.getJSON(url, 
    function(data) {
        // the code inside this function will be run,
        // when the $.getJSON finishes retrieving the data
        js = data;
        $("div").html(js);
    }
);

Assuming you want to receive data returned by $.getJSON in a javascript variable.

var js;

$.getJSON(url, function(data) {
    js = data;
    // you can even pass data as parameter to your target function like myFunct(data);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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