Get user ip with jquery

馋奶兔 提交于 2019-12-24 03:34:18

问题


I want 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.


回答1:


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);
  });



回答2:


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.




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/6160157/get-user-ip-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!