【问题标题】:How to get client IP address using jQuery如何使用 jQuery 获取客户端 IP 地址
【发布时间】:2010-12-11 03:25:35
【问题描述】:

我想知道如何使用 jQuery 获取客户端 IP 地址?

有可能吗?我知道纯 javascript 不能,但使用 Stack Overflow 本身的JSONP 获得了一些代码。

那么,有没有使用 jQuery 的解决方法?

【问题讨论】:

    标签: javascript jquery ip-address


    【解决方案1】:
    
    <html lang="en">
    <head>
        <title>Jquery - get ip address</title>
        <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
    </head>
    <body>
    
    
    <h1>Your Ip Address : <span class="ip"></span></h1>
    
    
    <script type="text/javascript">
        $.getJSON("http://jsonip.com?callback=?", function (data) {
            $(".ip").text(data.ip);
        });
    </script>
    
    
    </body>
    </html>
    

    【讨论】:

    • 您能否为您的回答提供一些背景信息。例如,它为什么起作用?有什么缺点吗?谢谢!
    【解决方案2】:

    jQuery 可以处理 JSONP,只需传递一个带有回调格式的 url=? $.getJSON 方法的参数,例如:

    $.getJSON("https://api.ipify.org/?format=json", function(e) {
        console.log(e.ip);
    });
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;

    这个例子是一个非常简单的 JSONP 服务,在 api.ipify.org 上实现。

    如果您不是在寻找跨域解决方案,则可以进一步简化脚本,因为您不需要回调参数,并且返回纯 JSON。

    【讨论】:

    • jsonip.appspot.com 显然也支持CORSJSONP
    • 服务器现在宕机了,这是个好主意,但我认为它不可靠。
    • 此服务器已关闭。所以我们可以简单地从 jsonip.appspot.com 中删除 apppot。所以它看起来像 jsonip.com?callback=?就是这样:)
    • @CMS 你应该回答你提供的api的请求限制。
    【解决方案3】:
    function GetUserIP(){
      var ret_ip;
      $.ajaxSetup({async: false});
      $.get('http://jsonip.com/', function(r){ 
        ret_ip = r.ip; 
      });
      return ret_ip;
    }
    

    如果你想使用 IP 并将其分配给变量,试试这个。只需拨打GetUserIP()

    【讨论】:

      【解决方案4】:

      对您的服务器进行简单的 AJAX 调用,然后通过服务器端逻辑来获取 IP 地址。

      $.getJSON('getip.php', function(data){
        alert('Your ip is: ' +  data.ip);
      });
      

      那么在php中你可能会这样做:

      <?php
      /* getip.php */
      header('Cache-Control: no-cache, must-revalidate');
      header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
      header('Content-type: application/json');
      
      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'];
      }
      print json_encode(array('ip' => $ip));
      

      【讨论】:

        猜你喜欢
        • 2012-03-14
        • 2012-02-16
        • 2016-01-12
        • 2021-07-05
        • 2017-12-20
        • 2019-01-14
        • 2015-12-20
        • 2016-03-29
        • 1970-01-01
        相关资源
        最近更新 更多