Possible Duplicate:
jQuery AJAX: return value on success
Im having this weird reference issue when im trying to get a JSON file through query:
var themeData;
$.getJSON("json/sample.js", function(data) {
themeData = data.theme;
console.log(themeData.sample[0].description);
});
console.log(themeData.sample[0].description);
The first console.log works, the second doesnt. Why is this happening?
It’s the second one (chronologically in your code) that doesn’t get hit. That’s because it hasn’t been set yet. The callback inside
getJSONgets invoked asynchronously after returning from the server.If you really need to call a method “after”
getJSON, then embrace the idea of callbacks. Use something like this.Edit
You could also force a synchronous call instead using
async: falseof the JQuery ajax function.