load json into variable
Solution 1:
This will do it:
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': my_url,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
The main issue being that $.getJSON
will run asynchronously, thus your Javascript will progress past the expression which invokes it even before its success
callback fires, so there are no guarantees that your variable will capture any data.
Note in particular the 'async': false
option in the above ajax call. The manual says:
By default, all requests are sent asynchronous (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Solution 2:
code bit should read:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
});