I’d like to store my json response in a global variable so, i could use it through my app without making a getJSON request more than once.
var data;
$.getJSON("panorama.json",function(json){
data = json.images[0].src;
console.log(data);
});
console.log(data);
If I log it in the actual request its fine, but i get “undefined” everywhere else.
Any comment appriciated.
Edit [copied from comments]: Tried …
$.myglobals = { result: "unset" }
$(document).ready(function() {
$.getJSON( "panorama.json", function(json) {
$.myglobals.result = json.images[0].src;
console.log($.myglobals.result);
});
console.log($.myglobals.result);
}) ;
The first log is okay, the second is undefined.
Edit [copied from answer]:
actually both method worked
the interesting thing is that my
request was in a function and i tried
to acces my global variable right
after the request in the same functionwhen i accesed it outside the function
it worked like a charm
If your real code is structured like that then you have a problem with trying to access the data that hasn’t been set yet. Just because your
$.getJSON()is aboveconsole.log()doesn’t mean that you get the response before you log value of data.So your problem is not scope, but rather the timing: introduce some server-side lag and your solution may as well crash.
Maybe you should set some flag if response was received: