从PHP返回的JSON对象为NULL

时间:2018-03-03 04:11:36

标签: javascript php json ajax google-api

我正在尝试使用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();
    }

1 个答案:

答案 0 :(得分:0)

您的AJAX表单看起来不对。请尝试阅读https://www.w3schools.com/js/js_json_php.asp

原始