问题
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