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", ...
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", ...
Share
Improve this question
edited Jul 18, 2014 at 5:33
brno792
asked Jul 18, 2014 at 5:08
brno792brno792
6,80918 gold badges57 silver badges72 bronze badges
2
-
The
function(data){...}
part is the callback of getJSON,data
is the JSON response that you will get. – Teh SoTo Commented Jul 18, 2014 at 5:10 -
You mean you want to receive data returned by
$.getJSON
in aJavaScript
variable? – AdityaParab Commented Jul 18, 2014 at 5:10
2 Answers
Reset to default 7You 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);
});