使用Cloudflare获得真正的国家

时间:2015-11-28 16:39:55

标签: javascript jquery ajax

如果我拨打链接http://freegeoip.net/json/,则会显示我的国家/地区正确无误。但是,如果我通过JavaScript在我的网站上调用它而不是向我显示USA(Cloudflare Server)。我如何通过这个来显示正确的国家?

<script>
    jQuery.ajax( { 
      url: '//freegeoip.net/json/', 
      type: 'POST', 
      dataType: 'jsonp',
      success: function(location) {
          $("div.country").html(location.country_name);
      }
    });
</script>
<div class="country"></div>

1 个答案:

答案 0 :(得分:1)

如果您从服务器拨打电话获取他们的IP,您需要执行类似的操作以获取您的用户IP并将其发送到freegeoip

<script>    
 function myIP() {
     if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
     else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

     xmlhttp.open("GET","http://api.hostip.info/get_html.php",false);
     xmlhttp.send();

     hostipInfo = xmlhttp.responseText.split("\n");

     for (i=0; hostipInfo.length >= i; i++) {
       ipAddress = hostipInfo[i].split(":");
       if ( ipAddress[0] == "IP" ) return ipAddress[1];
     }

     return false;
}

var ip  = myIP();

 jQuery.ajax( { 
      url: 'http://freegeoip.net/json/'+ip.replace(' ',''), 
      type: 'POST', 
      dataType: 'jsonp',
      success: function(location) {
          $("div.country").html(location.country_name);
      }
    });

  </script>
  <div class="country"></div>

因为上面的例子取决于服务http://api.hostip.info/get_html.php你可以添加一个简单的php脚本来获取你的用户ip地址

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}
   echo $ip;

再次更新你可以通过地理定位和反向地理编码示例应用程序获取所有信息,而无需他们的IP

<强>前端

<script>   
$( document ).ready(function() {    

if (navigator.geolocation) {
   navigator.geolocation.getCurrentPosition(showPosition);
} 

function showPosition(position) {
    jQuery.ajax( { 
      url: 'geocoder.php', 
      type: 'POST', 
      data:position,
      dataType: 'json',
      success : function(response) {
         $(".country").text(response.address.country);
         $(".postal_code").text(response.address.postcode);
      }

    })
}

})  

</script>
<div class="country"></div>
<div class="postal_code"></div>

<强> geocoder.php

<?php
$lat = $_POST['coords']['latitude'];
$long = $_POST['coords']['longitude'];
$url = "http://nominatim.openstreetmap.org/reverse?format=json&lat=".$lat."&lon=".$long;
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'examples');
$query = curl_exec($curl_handle);
curl_close($curl_handle);
$jsondata = json_decode($query,true);
echo json_encode($jsondata);


?>