我试图通过调用我自己的服务器从script.js进行iplookup,但返回的所有内容都是' 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 :(得分:1)
您还需要回应响应。现在你正在做的是,你设置标题,将$ _SERVER ['REMOTE_ADDR']编码为$ data变量,但你需要回复它。所以你的javascript ajax请求只获得一个空响应。
这样做:
<?php
header("Content-type: application/json");
print json_encode($_SERVER['REMOTE_ADDR']);
?>