Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load json into variable

I have to do something very simple, but there doesn't seem to be an easy way to do this, as far as I can tell. I just want to load JSON data from a remote source and store it in a global Javascript variable using jQuery. Here's what I have:

var my_json; $.getJSON(my_url, function(json) {   var my_json = json; }); 

The my_json variable remains undefined. I think this is clearly a scope issue. It seems to me the $.getJSON method should return JSON, but it returns an XMLHttpRequest object. If I do this:

request = $.getJSON(my_url); my_json = request.responseText.evalJSON(); 

That doesn't work because until the readystate == 4, the responsetext remains null. It seems you have to use the callback function to return the responsetext, since it fires on success.

It can't be this hard! Right?

like image 582
Aaron Avatar asked Feb 01 '10 15:02

Aaron


People also ask

How can I get data from JSON to variable?

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 $.

Can JSON use variables?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier. $vars can be used as: substitution variables for URI templates.


1 Answers

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.

like image 75
karim79 Avatar answered Sep 21 '22 05:09

karim79