0

我需要向 google places api 发出获取请求,但是我不能只使用 javascript,因为它不支持 jsonp。我读到我可以使用 php 文件执行获取请求,然后对其执行正常的 jquery ajax 调用以获取 json 数据。但是我使用创建了 php 文件

<?php
echo file_get_contents("https://maps.google...");
?>

然后对托管在我的 ubuntu 发行版上的 http:localhost/ 服务器上的该文件使用 jquery ajax 请求,但我收到 500 http 服务器错误。我做错了什么或者我该如何正确地做这件事?

</script>

      <script>
      $(document).ready(function(){

      $.ajax({
      url: 'http://localhost/places.php',
      dataType: "json",
      type: "GET",
      success: function( data){
      document.getElementById("paragraph").innerHTML= data.result[0].name;
      },
      error: function(request, status, error){
      document.getElementById("paragraph").innerHTML= "error";
      }
      })


      });

</script>
    <body>
    <p id="paragraph">
       Untouched Text.
    </p>
    <button id="b1">Click Me!</button>
    </body>

我使用 firebug 得到的唯一错误消息是 500 Internal Server Error 所以我不认为它是我的 html、javascript 或 jquery。

4

1 回答 1

0

您正在调用 Google API 并且必须返回一个 JSON,所以这应该足够了:

<?php
    $json = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false");

    $data = json_decode($json);

    // manipulate data and rebuild json with $json = json_encode($data) if needed

    Header("Content-Type: application/json");
    die($json);
?>

这很有效,因为谷歌用正确格式的 JSON 来回答我:

{

    "results": [ ],
    "status": "REQUEST_DENIED"
}

通过正确的 API Key 配置,您应该可以正常工作。检查调用是否在您的浏览器中运行(没有 cookie 等 - 一个干净的会话,这file_get_contents()将给您)并且您的 PHP 安装能够恢复 SSL 数据(它应该,但让我们检查一下),即,

file_get_contents("https://www.google.com/");

应该恢复谷歌的主页。

此呼叫不需要身份验证(有速率限制,但我认为您不太可能进行所有需要的呼叫以将您拒之门外):

http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false

上面将返回一个非常复杂的 JSON,其中可能包含重音字符。现在我想到它,Header上面会更好:

    Header('Content-Type: application/json;charset=UTF-8');
于 2012-11-14T09:15:10.027 回答