javascript - Storing $.getJSON() response to local var -
this question has answer here:
- how return response asynchronous call? 21 answers
i need use function several times , wanted avoid writing same method on , over. wanted use $.getjson() response , store in var returned. way can call method.
function startfilter(){ var grid = []; $.getjson('data/griddata1.json',function(json){ grid = json; console.log(grid); }); console.log(grid); return grid; }
the grid var set inside of .getjson not outside of .getjson. ideas why, , if more info needed let me know?
the ajax calls async. here how things positioned in time.
function startfilter(){ var grid = []; // (1) $.getjson('data/griddata1.json', function(json){ // (2) grid = json; // (5) console.log(grid); // (6) }); console.log(grid); // (3) return grid; // (4) }
you should use callbacks build logic:
function startfilter(callback) { $.getjson('data/griddata1.json', callback); } var grid = []; startfilter(function(json) { grid = json; // logic here });
Comments
Post a Comment