【问题标题】:Redirect URL based on JSON callback data基于 JSON 回调数据的重定向 URL
【发布时间】:2019-10-22 11:12:23
【问题描述】:

我尝试使用 JavaScript 按国家/地区重定向访问者

以下调用检查访问者所在国家/地区的 IP,例如CN(中国)并将其重定向到其他网站。

<script async src="https://get.geojs.io/v1/ip/country.js"></script>

<script type="application/javascript">
  function geoip(json) {
    var countrycode.textContent = json.country;
  }

  if (countrycode.textContent == "CN") {
    window.location = "http://baido.com"
  }
</script>

有什么帮助吗?

【问题讨论】:

  • 有时您需要致电geoip
  • 怎么做?。
  • 实际上,他不必调用函数,库已经这样做了。

标签: javascript json geoip


【解决方案1】:

我看到有一个标记为已解决的答案,但我仍然无法让它发挥作用。所以我创建了这个,以防你想往另一个方向发展:

  function geoip() {
  
   $.ajax({
        type: 'get',
        url: 'https://get.geojs.io/v1/ip/country.json',
        success: function(data) {
            if (data['country'] == "CN") {
              window.location = "https://baido.com/";
            }
    	}
    });
    }
    
geoip();
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;

【讨论】:

    【解决方案2】:

    问题是您没有正确使用示例代码。 countrycode.textContent 部分应该在浏览器上显示用户的国家代码,这意味着它不适用于您的用例,因为您正在尝试重定向。

    另请注意,geoip 函数由您从 geojs 加载的脚本使用,因此如果您尝试重定向,则应在该函数中执行此操作。

    这是更新后的代码。

    
        <script type="application/javascript">
            function geoip(json){
                if (json.country_code == "CN") {
                  window.location = "http://baido.com/";
                }
            }
        </script>
        <script async src="https://get.geojs.io/v1/ip/geo.js"></script>
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 2021-07-29
      相关资源
      最近更新 更多