google places api error with jquery ajax call… html_attributions

后端 未结 1 985
梦如初夏
梦如初夏 2021-01-16 13:16

I\'m using the new google places api with jquery/ajax. When I run this code:

$.ajax({
url: \"https://maps.googleapis.com/maps/api/place/search/json?location         


        
相关标签:
1条回答
  • 2021-01-16 13:58

    It seems like the places api does not support ajax so far.

    It not enough that the server responds with proper JSON. The answering server has to support JSONP and surround the JSON answer with a callback generated by jQuery. The response must look like that:

    jQuery17101705844928510487_1324249734338({"data":"whatever"});
    

    The hack that JSONP does, is to interpret the response as script, because the script-Tag is not affected by the Same-Origin-Policy. Without the callback you have no chance to do that in the browser.

    If its not supported you have to do the requests from your server..

    Server-Example with PHP:

    <?php
    header("Content-Type:text/javascript"); // avoid browser warnings
    $request = new HttpRequest("http://programmingisart.com/json-data-source.php", HttpRequest::METH_GET);
    $request->send();
    $json_data = $request->getResponseBody();
    
    // wrap the data as with the callback
    $callback = isset($_GET["callback"]) ? $_GET["callback"] : "alert";
    echo $callback."(".$json_data.");";
    

    Client-Example with jQuery:

    <div id="json-result"></div>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
                dataType: "jsonp",
                url: "jsonp-wrapper.php",
                success: function(data) {
                    $("#json-result").html(JSON.stringify(data));
                },
                error: function() {
                    alert("error");
                }
            });
        });
    </script>
    

    You can replace the PHP-code with any other server-platform and do the required steps.

    • HTTP-Request to a JSON source
    • Wrap the JSON as with a callback-function
    0 讨论(0)
提交回复
热议问题