如何使用php进行获取请求然后使用jquery访问它?

时间:2012-11-14 08:47:46

标签: php jquery ajax json

我需要向google地址api发出get请求但是我不能只使用javascript,因为它不支持jsonp。我读到我可以使用php文件做一个get请求,然后对它进行正常的jquery ajax调用以获取json数据。但是我使用

创建了php文件
<?php
echo file_get_contents("https://maps.google...");
?>

然后在我的ubuntu发行版上使用jquery ajax请求到我的http:localhost / server上托管的这个文件,但是我收到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内部服务器错误,所以我不认为它是我的html,javascript或jquery。

1 个答案:

答案 0 :(得分: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密钥配置,您应该能够正常工作。检查呼叫是否在您的浏览器中工作(没有cookie等 - 一个干净的会话,这是file_get_contents()将给你的),并且您的PHP安装能够恢复SSL数据(它应该,但是让我们检查),即

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

应该恢复Google的主页。

此通话不需要身份验证(有速率限制,但我认为您不可能进行所有必要的呼叫以阻止您关闭):

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

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

    Header('Content-Type: application/json;charset=UTF-8');