简体   繁体   English

将json响应存储到对象,以便可以从对象获取值

[英]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. 我正在尝试获取将响应JSON数据的地名API。 I create a dataStorage Object and put the response in it. 我创建一个dataStorage对象,并将响应放入其中。 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: JSON响应如下所示:

{  
   "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.. 如果你正在寻找“一”作为国家代码,那么你的查询将进一步不会work..You将迭代通过JSON并检查值.. in只检查键..

Your main issue is that the ajax request is asynchronous . 您的主要问题是ajax请求是异步的 This means that the function CountryQuery returns immediately, before the request returns the JSON value. 这意味着函数CountryQuery在请求返回JSON值之前立即返回。 You have to get the value from dataStorage inside the success function: 您必须从成功函数内的dataStorage获取值:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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