我想知道如何使用jQuery获取客户端IP地址?
有可能吗?我知道纯JavaScript不能,但从Stack Overflow得到了一些使用JSONP
的代码。
那么,是否有使用jQuery的解决方法?
我想知道如何使用jQuery获取客户端IP地址?
有可能吗?我知道纯JavaScript不能,但从Stack Overflow得到了一些使用JSONP
的代码。
那么,是否有使用jQuery的解决方法?
$.getJSON("https://api.ipify.org/?format=json", function(e) {
console.log(e.ip);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这个例子展示了一个非常简单的JSONP服务,使用api.ipify.org
实现。
如果您不需要跨域解决方案,则可以进一步简化脚本,因为您不需要回调参数,并且可以返回纯JSON。
进行一个简单的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));
function GetUserIP(){
var ret_ip;
$.ajaxSetup({async: false});
$.get('http://jsonip.com/', function(r){
ret_ip = r.ip;
});
return ret_ip;
}
GetUserIP()
即可。
<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>
jsonip.appspot.com
显然支持CORS
和JSONP
。 - hippietrail