【问题标题】:JSON Object returned from PHP is NULL从 PHP 返回的 JSON 对象为 NULL
【发布时间】: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


【解决方案1】:

您的 AJAX 表单看起来有问题。尝试阅读https://www.w3schools.com/js/js_json_php.asp

原创。

【讨论】:

  • 我正在使用回调。你能指出为什么返回的 JSON 是 NULL 吗?
  • 我收到此错误:InvalidStateError: responseText 仅在 responseType 为 '' 或 'document' 时可用。
  • 在你的 php 代码中,$jsonPlacesObject=json_decode(htmlspecialchars(@file_get_contents($url),true),true);我认为 file_get_contents 不适合该工作,请尝试 curl。它为此而建。您可能无法得到预期的正确响应。
  • 不,结果仍然是 NULL。
  • 卷曲打开了吗?
猜你喜欢
  • 2021-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
相关资源
最近更新 更多