jquery - Load JSON file within Javascript -
jquery - Load JSON file within Javascript -
this question has reply here:
how homecoming response asynchronous call? 11 answersi want load local json file config info usage in javascript file.
i tried this:
var map; var initialmapcoordinates = ""; function loadconfigfile() { $.getjson('js/config.json', function(jd) { initialmapcoordinates = jd.googlemaps.initialcoordinates; initmap(); }); }; function initmap() { google.maps.visualrefresh = true; var mapoptions = { center: new google.maps.latlng(initialmapcoordinates), zoom: 10, maptypeid: google.maps.maptypeid.roadmap }; var mapelement = document.getelementbyid('map'); map = new google.maps.map(mapelement, mapoptions); } google.maps.event.adddomlistener(window, 'load', loadconfigfile()); i want assign different elements of config file variables utilize them in script. there still fail. tried utilize global variable, seem wrong here.
how contents of jd.googlemaps.initialcoordinates variable work outside function?
expanding upon comment: accessing global variable before before had chance set async request. need check create sure has loaded, there serveral ways handle this, should create sure javascript needs config file not fire until variables have been loaded. so, wrap map functionality in init() function , phone call after have set global.
var configdata = ""; function loadconfigfile() { $.getjson('js/config.json', function(jd) { configdata = jd.googlemaps.initialcoordinates; init(); }); }; function init() { console.log(configdata); } a little more on async. basically, causes problem function sets global variable not called until result received. since javascript operates on single thread, not want block rest of scripts running because freeze page. means rest of scripts after .getjson executed before json file loaded.
so in practice, order of execution original script run this:
first: var configdata = ""; second/third: loadconfigfile() , getjson(); fourth: log configdata console; fifth: set config info json file. var configdata = ""; //first function loadconfigfile() { //second $.getjson('js/config.json', //third function(jd) { configdata = jd.googlemaps.initialcoordinates; //fifth }); }; console.log(configdata); //fourth update three:
do this.
function loadconfigfile() { $.getjson('js/config.json', function(jd) { initialmapcoordinates = jd.googlemaps.initialcoordinates; initmap(); //remove loadconfig function console.log(initialmapcoordinates) //now available!; }); console.log(initialmapcoordinates) //not available!; }; javascript jquery
Comments
Post a Comment