看着你的評論我看到你的代碼是錯誤的,它的jQuery不是PHP:
<!DOCTYPE HTML>
<head>
<title>
Test
</title>
<body>
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
<?php
$.get("http://ipinfo.io", function (response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
}, "jsonp");
?>
伊夫放在一起友好的API消費者的例子,這將緩存60secs的結果(真的,你應該增加到86400 = 1天以節省寶貴的請求配額),這將加快後續的重新加載STS &不轟擊API上http://ipinfo.io/developers
如說,你被限制在每天1000個API請求......
<?php
if($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['ip'])){
header('Content-Type: application/json');
if($_POST['ip'] == $_SERVER['REMOTE_ADDR']){
//fix ip6 address for testing
$_POST['ip'] = ($_POST['ip']='::1') ? '127.0.0.1' : $_POST['ip'];
//cache path
$cache_folder = dirname(__FILE__) . '/cache';
//cache file, this will store the API response for the ip
$cache_file = $cache_folder.'/'.$_POST['ip'].'.json';
//check folder exists
if(!file_exists($cache_folder)){mkdir($cache_folder, 0755);}
//do if cache files not found or older then 60 seconds (60 should suffice)
if(!file_exists($cache_file) || filemtime($cache_file) < (time() - 60)){
//query API, apending the users IP address to the url
$data = file_get_contents('http://ipinfo.io/'.$_POST['ip']);
//store for future use
file_put_contents($cache_file, $data);
}else{
$data = file_get_contents($cache_file);
}
exit($data);
}else{
exit(array('access denied, missing $_POST[\'ip\']'));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(function(){
$.post("index.php", { 'ip': '<?php echo $_SERVER['REMOTE_ADDR'];?>' },
function(response) {
$("#ip").html("IP: " + response.ip);
$("#address").html("Location: " + response.city + ", " + response.region);
$("#details").html(JSON.stringify(response, null, 4));
});
});
</script>
</head>
<body>
<h3>Client side IP geolocation using <a href="http://ipinfo.io">ipinfo.io</a></h3>
<hr/>
<div id="ip"></div>
<div id="address"></div>
<hr/>Full response: <pre id="details"></pre>
</body>
</html>
你甚至可以從一個髒文件緩存變爲持久性高速緩存和存儲結果在數據庫中。
希望它有幫助,快樂的編碼!
相同的來源政策,您需要使用PHP代理json到您的jQuery中。 –
@LozCherone這是一個jsonp請求,所以sop不適用 – Drahcir
它做什麼,你不指望,或者它不是你期望的做什麼?你有沒有看到任何錯誤? – Jason