I want to store the JSON file in a variable, and use it later in the script. But the variable just shows up as undefined.
Here's what I have done.
var citiesList;
var countryList;
$.getJSON("http://localhost:80/weather/js/country.json", function(data){
citiesList = data;
countryList = Object.keys(citiesList.countries);
});
Now when i try to access the contents of citiesList
, an error shows up saying cannot read property length of undefined.
This is how I try to access the contents
var country = $('#countrySelect').val();
$('#citySelect').html('');
for (var i = 0; i < citiesList.countries[country].length; i++) {
$('#citySelect').append('<option>' + citiesList.countries[country][i][0] + '</option>');
}
The same exact code works when async is set to false. But I am looking for the proper way of using getJSON to avoid such errors.
Thanks in advance guys.