JS異步請求自己站的ip/index.php接口,而自己站接口通過PHP在淘寶API上獲取歸屬地查詢
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>ip2</title>
<script type="text/javascript">
function showJson(){
var test;
if(window.XMLHttpRequest){
test = new XMLHttpRequest();
}else if(window.ActiveXObject){
test = new window.ActiveXObject();
}else{
alert("請升級至最新版本的瀏覽器");
}
if(test !=null){
test.open("GET",location.protocol+'//'+location.hostname+'/ip/index.php',true);
test.send(null);
test.onreadystatechange=function(){
if(test.readyState==4&&test.status==200){
var data = JSON.parse(test.responseText);
document.getElementById("address").innerHTML = "IP:" + data.data.ip+data.data.region+data.data.city+'['+data.data.isp+']';
}
};
}
}
window.onload=function(){
showJson();
};
</script>
</head>
<body>
<center id="address"></center>
</body>
</html>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<title>ip</title>
<script type="text/javascript" src="/uploads/allimg/200915/1534543445-0.jpg"></script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type : 'get',
url : location.protocol+'//'+location.hostname+'/ip/index.php',
dataType : 'json',
success : function(data) {
if (data.code==0) {
var str = '';
if (data.data.country_id=='CN') {
str += data.data.ip+data.data.region+data.data.city+'['+data.data.isp+']';
} else {
str += data.data.country+' '+data.data.area;
}
$('#address').text("IP:"+str)
} else {
$('#address').text('(沒查到)');
}
},
error : function(data) {
console.log(data);
}
});
});
</script>
</head>
<body>
<center id="address"></center>
</body>
</html>
PHP代碼-/ip/index.php-放在自己的網(wǎng)站里
<?php
function getip(){
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$ip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$ip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '127.0.0.1';
}
$ip = getip();
$ipjson = file_get_contents('http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip);
echo $ipjson;
die();
版權(quán)聲明: 本站資源均來自互聯(lián)網(wǎng)或會員發(fā)布,如果侵犯了您的權(quán)益請與我們聯(lián)系,我們將在24小時內(nèi)刪除!謝謝!
轉(zhuǎn)載請注明: js用php+ajax利用淘寶IP庫獲取訪客ip和所在地