简体   繁体   中英

Store json response to object so can get the value from the object

I am trying the get the geonames' API which will response JSON data. I create a dataStorage Object and put the response in it. Currently I have problem when getting the value from the storing object.

Here is my code:

var dataStorage = new Object();

function CountryQuery(geoId, geoCode) {
  $.ajax({
    type: "GET",
    url: "http://api.geonames.org/childrenJSON?geonameId=" + geoId + "&username=tompi",
    dataType: "json",
    success: function(data) {
      dataStorage[geoCode] = data;
    }
  });
}

if (!('AN' in dataStorage)) {
  CountryQuery(6255152, "AN");
}

$(dataStorage).find('AN').geonames.countryName;

The JSON response is look like below:

{  
   "totalResultsCount":2,
   "geonames":[  
      {  
         "countryId":"6697173",
         "countryCode":"AQ",
         "name":"Antarctica",
         "countryName":"Antarctica"
      },
      {  
         "countryId":"3371123",
         "countryCode":"BV",
         "name":"Bouvet Island",
         "countryName":"Bouvet Island"
      }
   ]
}

Try this :

dataStorage.push(geoCode,data);

instead of:

dataStorage[geoCode] = data;

and if you are looking for 'AN' as country code then your query will further not work..You will have to iterate through the JSON and check for the values.. in only checks the keys..

Your main issue is that the ajax request is asynchronous . This means that the function CountryQuery returns immediately, before the request returns the JSON value. You have to get the value from dataStorage inside the success function:

var dataStorage = {};

function countryQuery(geoId, geoCode, callback) {
    $.ajax({
        type: 'GET',
        url: 'http://api.geonames.org/childrenJSON?geonameId=' + geoId + '&username=tompi',
        dataType: 'json',
        success: function(data) {
            dataStorage[geoCode] = data;
            callback();
        }
    });
}

function useDataStorage() {
  alert(dataStorage.AN.geonames[0].countryName);
}

if (dataStorage.AN === undefined) countryQuery('6255152', 'AN', useDataStorage);
else useDataStorage();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM