利用js获取客户端ip的方法

获取ip有两种方式,下面分别对每种方法进行研究。

1. 通过script标签引入url

比如如下代码:

 
 
<scripttype="text/javascript" src="http://pv.sohu.com/cityjson?ie=utf-8"></script>  
<scripttype="text/javascript">  
    alert(returnCitySN.cip);//弹出本机ip
</script>

该链接返回的数据为本地ip以及地域信息

var returnCitySN = {"cip": "36.44.80.58", "cid": "610000", "cname": "陕西省"};

也有的网站服务提供回调函数的,比如http://freegeoip.net。这个网站支持json,xml,csv,jsonp格式。我们可以将上面的url换成http://freegeoip.net/json/?callback=foo

<scripttype="text/javascript" src="http://freegeoip.net/json/?callback=foo"></script>  
<scripttype="text/javascript">  
    function foo(json){
      alert(json.ip); // alerts the ip address
    }  
</script>

2. ajax调用

如果该url返回的是json格式的数据,要想调用,就需要用到ajax。

<script >
    $.getJSON('//freegeoip.net/json/', function(data) {
        console.log(JSON.stringify(data, null, 2));
    });
</script>
  • 1
  • 2
  • 3
  • 4
  • 5

以上的代码其实是简写的ajax,写成ajax:

$.ajax({
    url: 'http://freegeoip.net/json/',
    success: function(data){
       console.log(JSON.stringify(data));
    },
    type: 'GET',
    dataType: 'JSON'
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

值得一提的是当dataType和type的选择会影响能不能从服务器返回数据。比如当dataType为json,type为post,则freegeoip不能返回数据。别的服务器比如//gd.geobytes.com/GetCityDetails则是当dataType为json的时候都不能返回。这个应该和服务的后台支持有关系。 
还有一些东西,比如//gd.geobytes.com/GetCityDetails如果不加?callback=? getJson就返回不了东西,这些都是写服务器支持的问题,就不研究了。
                                                                                                                                君凯商联网 - Alex.Ma


猜你喜欢

转载自blog.csdn.net/weixin_41756610/article/details/80346698