javascript - $.getJSON return value to variable -


this question has answer here:

here's problem

i have json file full of country codes, , function gets random country code, this:

function getrandomcountrycode(specificmap){   $.getjson('../maps/' + specificmap + '.json', function( data ) {     var countries = [];     (var in data.country) {       countries.push(data.country[i].code);     }     var rndcountrycode = countries[math.floor(math.random()*countries.length)];     return rndcountrycode;   }); }; 

in function, call above function , try store rndcountrycode variable variable it's available inside new function.

function loadmap(map){   var specificmap = map;   var y = getrandomcountrycode(specificmap);   console.log("y : " + y); } 

all undefined. did lot of research (here , here , here) , realized because of asynchronous nature of $.getjson, , should use callbacks life of me can't figure out.

thanks help.

put code going after

var y = getrandomcountrycode(specificmap); 

in success callback

function getrandomcountrycode(specificmap){   $.getjson('../maps/' + specificmap + '.json', function( data ) {     var countries = [];     (var in data.country) {       countries.push(data.country[i].code);     }     var rndcountrycode = countries[math.floor(math.random()*countries.length)];     >>>console.log("rndcountrycode  : " + rndcountrycode );     return rndcountrycode;   }); }; 

since getjson asynchronous , dont know when response back, way guarantee code manipulating response work putting in success handler(the second parameter getjson).

the success handler exucuted when there has been successful response regardless of how long took.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -