【发布时间】:2018-03-03 04:11:36
【问题描述】:
我正在尝试使用 AJAX 向 PHP 发送一个 javascript 变量(placeid)。我使用此变量来检索 JSON 对象。返回给 Javascript 的 JSON 为 NULL。我该如何解决这个问题?
function sendToPhp(placeid){
var url = "finals.php?placeid="+placeid;
var getJSONObj=function(url,callback){
var httpc = new XMLHttpRequest();
httpc.open("GET", url, true);
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.responseType='json';
httpc.onload= function(){
var status=httpc.status;
if(status==200){
//alert(httpc.response);
callback(null,httpc.response);
}
else{
callback(status,httpc.response);
}
};
httpc.send();
};
getJSONObj(url,function(err,jsonObjectReturned){
if(err!==null){
alert("something went wrong"+ err);
}
else
{
alert("success");
alert(jsonObjectReturned); // **returns NULL**
}
});
} // end of function
PHP 脚本使用 placeid 返回一个 JSON 文件,如图所示:
if(isset($_GET['placeid']))
{
$placeid= $_GET['placeid'];
$apikey="someKeyValue";
$url="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=".$apikey;
$jsonPlacesObject=json_decode(htmlspecialchars(@file_get_contents($url),true),true);
echo json_encode($jsonPlacesObject); //sending json to javascript**
die();
}
【问题讨论】:
-
如果
**//sending json to javascript**在您的文档中,则您的脚本无效。另外你为什么解码json然后重新编码呢?事实上,你为什么不直接使用谷歌地图 API? -
@Scuzzy 将其转换为字符串
-
Thak 对我来说毫无意义。
-
不要尝试同时调试多个东西。脚本是否接收到
placeid?$jsonPlacesobject的内容是什么?如果这些都是您所期望的,那么请诊断 AJAX。但我敢打赌,您没有得到有效的 JSON 数据。 -
@TimMorton JSON 有效且不为空。
标签: javascript php json ajax google-api