开发者

Get user ip with jquery

开发者 https://www.devze.com 2023-03-08 18:29 出处:网络
I wan开发者_JAVA百科t to get the user\'s IP address with jQuery or JavaScript, it doesn\'t really matter but I prefer jQuery.

I wan开发者_JAVA百科t to get the user's IP address with jQuery or JavaScript, it doesn't really matter but I prefer jQuery.

I've seen some answers here but they didn't work for me.


This has been taken from How to get client IP address using jQuery

$.getJSON("http://jsonip.appspot.com?callback=?",
    function(data){
       alert( "Your ip: " + data.ip);
  });


That isn't exposed to javascript, but if you really need it you could spit it out in your markup (assuming php):

<head>
<meta name="ip" content="<?php echo $_SERVER["REMOTE_ADDR"] ?>">
–
<script>$(function(){ alert( $("meta[name=ip]").attr("content") ) })</script>

Not sure why you would want to though, javascript runs on the client, so when would you need its ip? From javascript's perspective, it is safe to assume that the user's ip is 127.0.0.1.


You cannot do it with just client side code.. you would need to user a server side page and use jquery to load the value into a div using jsonP or something


My personal favorite (comes with some bonus'!):


$.ajax({
    dataType: 'json',
    url: 'http://api.hostip.info/get_json.php',
    success: function(data) {
        var $ip = data['ip'],
            $city = data['city'],
            $countryCode = data['country_code'],
            $countryName = data['country_name'];
    }
});

Example Example Example

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号