如何获取访问者的网站国家/地区名称

时间:2017-04-18 07:29:05

标签: javascript php jquery html geolocation

我目前正在我的网站上工作,根据访问者的国家/地区显示各种地方。

我也试过这个例子,但我想自动获取IP地址

这里是示例代码

HTML

<input type="text" id="ip" />
<input type="button" value="Get country of IP" id="submit" />

的JavaScript

<script type="text/javascript">
$(function() {
  $("#submit").click(function() {
    if ($('#ip').val()) {
      var ip = $('#ip').val();

      // the request will be to http://www.geoplugin.net/json.gp?ip=my.ip.number but we need to avoid the cors issue, and we use cors-anywhere api.

      $.getJSON("https://cors-anywhere.herokuapp.com/http://www.geoplugin.net/json.gp?ip=" + ip, function(response) {
        console.log(response);
        // output an object which contains the information.
        $("#content").html("Hello visitor from " + response.geoplugin_countryName);

      });
    } else {
      alert("Please provide a IP");
    }
  });
});

</script>

我是PHP的新手,所以请指导我..谢谢:)

1 个答案:

答案 0 :(得分:5)

尝试以下代码

let a = new Array(3);
a.join('.').split('.').map(v => 1);

let a = new Array(3);
a.fill(1);

let a = new Array(3);
a.fill(undefined).map(v => 1);

let a = new Array(3);
[...a].map(v => 1);
// Jquery
$.getJSON("http://freegeoip.net/json/", function(data) {
  var ip = data.ip;
  var country = data.country_name;
  $("#ip").val(ip);
  $("#content").html("Hello visitor from " + country);
});