2014-09-10 60 views
-2

我試圖通過調用我自己的服務器從script.js做iplookup,但所有返回的是'undefined'。爲什麼?從PHP返回undefined的IP查找返回undefined

iplookup.php

<?php 
    header('content-type: application/json; charset=utf-8'); 
    $data = json_encode($_SERVER['REMOTE_ADDR']); 
    //next line needs to be commented out 
    //echo $_GET['callback'] . '(' . $data . ');'; 
?> 

的script.js

//get ipaddress 
$.ajax({ 
    url: "http://www.example.com/iplookup.php", 
    data: null, 
    type: 'GET', 
    crossDomain: true, 
    dataType: 'jsonp' 

}).done(function (json) { 
    self.ip = json; 
}); 
//on the next line it returns `undefined` 
console.log('ipaddress: ' + self.ip); 
+0

因爲你不是在你的PHP呼應任何東西了。 – 2014-09-10 14:13:25

+0

爲什麼'jsonp'?它究竟在哪裏返回'undefined'? – deceze 2014-09-10 14:13:28

+0

當您嘗試回顯它時,$ data的響應是什麼? – 2014-09-10 14:13:49

回答

1

您需要呼應反應出也。現在你在做什麼,是你設置頭文件,編碼$ _SERVER ['REMOTE_ADDR']到$ data變量,但是你的neber將它回顯出來。所以你的javascript ajax請求只能得到一個空的響應。

做像這樣:

<?php 

header("Content-type: application/json"); 
print json_encode($_SERVER['REMOTE_ADDR']); 

?>