我如何 use/store JSON 响应的值?

How do I use/store the value of a JSON response?

我想根据他们的 geoIP 确定我网站的访问者来自哪个国家/地区,这样我就可以确定该访问者是否正在访问他们特定国家/地区的网站,并通过确认弹出窗口提示他们是否如果他们不是,他们希望被重定向。然而,我的 JavaScript 知识是 limited/minimal。我如何 store/use 和 return 从 JSON 响应中动态使用特定值?

例如,我想使用以下国家 iso 代码 "US"。

"country": {
    "iso_code": "US",

将 MaxMind 的 GeoIP2 JavaScript Client API 与以下 JavaScript 结合使用:

<script type="text/javascript" src="//js.maxmind.com/js/apis/geoip2/v2.1/geoip2.js"></script>

<script type="text/javascript">

var onSuccess = function(location){
  console.log(
  "Lookup successful:\n\n"
  + JSON.stringify(location, undefined, 4)
  );
};

var onError = function(error){
  console.log(
      "Error:\n\n"
      + JSON.stringify(error, undefined, 4)
  );
};

geoip2.city(onSuccess, onError);

</script>

这个 JSON returned 看起来像这样:

{
  "city": {
    "geoname_id": 5368361,
    "names": {
      "es": "Los Ángeles",
      "fr": "Los Angeles",
      "ja": "ロサンゼルス",
      "pt-BR": "Los Angeles",
      "ru": "Лос-Анджелес",
      "zh-CN": "洛杉矶",
      "de": "Los Angeles",
      "en": "Los Angeles"
    }
  },
  "continent": {
    "code": "NA",
    "geoname_id": 6255149,
    "names": {
      "fr": "Amérique du Nord",
      "ja": "北アメリカ",
      "pt-BR": "América do Norte",
      "ru": "Северная Америка",
      "zh-CN": "北美洲",
      "de": "Nordamerika",
      "en": "North America",
      "es": "Norteamérica"
    }
  },
  "country": {
    "iso_code": "US",
    "geoname_id": 6252001,
    "names": {
      "ru": "США",
      "zh-CN": "美国",
      "de": "USA",
      "en": "United States",
      "es": "Estados Unidos",
      "fr": "États-Unis",
      "ja": "アメリカ合衆国",
      "pt-BR": "Estados Unidos"
    }
  },
  "location": {
    "accuracy_radius": 50,
    "latitude": 34.0669,
    "longitude": -118.3109,
    "metro_code": 803,
    "time_zone": "America/Los_Angeles"
  },
  "postal": {
    "code": "90020"
  },
  "registered_country": {
    "iso_code": "US",
    "geoname_id": 6252001,
    "names": {
      "ja": "アメリカ合衆国",
      "pt-BR": "Estados Unidos",
      "ru": "США",
      "zh-CN": "美国",
      "de": "USA",
      "en": "United States",
      "es": "Estados Unidos",
      "fr": "États-Unis"
    }
  },
  "subdivisions": [
    {
      "iso_code": "CA",
      "geoname_id": 5332921,
      "names": {
        "zh-CN": "加利福尼亚州",
        "de": "Kalifornien",
        "en": "California",
        "es": "California",
        "fr": "Californie",
        "ja": "カリフォルニア州",
        "pt-BR": "Califórnia",
        "ru": "Калифорния"
      }
    }
  ],
  "traits": {
    "autonomous_system_number": 7018,
    "autonomous_system_organization": "AT&T Services, Inc.",
    "isp": "AT&T Services",
    "organization": "AT&T Internet Services",
    "ip_address": "12.125.142.34"
  },
  "represented_country": {
    "names": {}
  }
}

GeoIP2 JavaScript Tutorial

提前致谢。

您已经有一个 Json,那么您可以这样做:

var onSuccess = function(location){
  console.log(location.country.iso_code);
};

沉迷于Emeeus的回答,如果你想将响应保存在本地以避免重复请求服务器或向用户询问两次相同的问题,你可以使用window.localStorage object. This object will persist data in the user browser even when user closes the browser, and data will be available for your domain. If you want to store just while user is browsing your site in that moment, and clear on close, use sessionStorage

您应该始终将字符串传递给 localStorage 的字段。您的代码类似于:

var geoData;
var onSuccess = function(location){
  window.localStorage.geoData = JSON.stringify(location);
  // ... do whatever you want with location ...
};

// ... on error ...

if (! window.localStorage.geoData)
  geoip2.city(onSuccess, onError);
else
  onSuccess(JSON.parse(window.localStorage.geoData));

请记住,如果 JSON 无效,JSON.parse 会引发错误。我建议你把代码用try {...} catch (e) {geoip2.city(onSuccess, onError)}括起来,就好像parse失败了,它会执行catch,可以正常向服务器请求数据。