【问题标题】:How to display a dynamic image based on geo location?如何根据地理位置显示动态图像?
【发布时间】:2021-01-27 04:28:08
【问题描述】:

我正在尝试根据用户访问我网站的国家/地区显示特定图片。我已经设法使用 ajax 和 https://geolocation-db.com/jsonp/ 来捕获位置信息。

如果我从美国或任何其他国家/地区检查此内容,我可以输出该国家/地区(使用 TunnelBear),但我的目标是根据输出国家/地区显示不同的图像。

我错过了什么?

//get ip, city, state & country
$.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function (location) {
        $("#country").html(location.country_name);
    },
});

let getCountry = location.country_name;

if (getCountry == 'United States') {
    bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
} else if (getCountry == 'United Kingdom') {
    bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
} else {
    bg.innerHTML = `<h3>This is not working!</h3>`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <div id="country"></div>
        <div id="bg"></div>

【问题讨论】:

  • 您可以为不同的国家/地区使用开关盒,但这将是很多工作。顺便说一句,比较时最好使用country_code
  • country_code 不是此 API 返回数据的一部分。您还有其他 API 建议吗?
  • 您无法在 ajax 调用之外获取 location 对象。您需要在success 方法中编写最后的代码块

标签: javascript ajax api geolocation


【解决方案1】:

需要在success方法里面勾选国家。

//get ip, city, state & country
$.ajax({
    url: "https://geolocation-db.com/jsonp",
    jsonpCallback: "callback",
    dataType: "jsonp",
    success: function (location) {
      $("#country").html(location.country_name);
      let getCountry = location.country_name;

      if (getCountry == 'United States') {
          bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED STATES">`;
      } else if (getCountry == 'United Kingdom') {
          bg.innerHTML = `<img src="https://via.placeholder.com/900x450?text=UNITED KINGDOM">`;
      } else {
          bg.innerHTML = `<h3>This is not working!</h3>`;
      }
    },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="country"></div>
<div id="bg"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2022-12-29
    • 2013-07-30
    • 1970-01-01
    • 2021-07-28
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多