我想知道如何使用 jQuery 获取客户端 IP 地址?
是否可以?我知道纯 javascript 不能,但是JSONP从 Stack Overflow 本身获得了一些代码。
那么,有没有使用 jQuery 的解决方法?
我想知道如何使用 jQuery 获取客户端 IP 地址?
是否可以?我知道纯 javascript 不能,但是JSONP从 Stack Overflow 本身获得了一些代码。
那么,有没有使用 jQuery 的解决方法?
jQuery 可以处理 JSONP,只需传递一个带有 callback=? $.getJSON方法的参数,例如:
$.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;
}
如果要使用 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>