Google Places API: json error Uncaught SyntaxError Unexpected token

I dont get why i get so many different errors. I'm using Google Places API for a test, and using simply an ajax query call with callback, i receive back the json but in CHrome browser i get

"Uncaught SyntaxError: Unexpected token :"

why the hell is that? I supposed Google does it right, and their json must be correct...so where could be the problem?

this is my code

$.ajax({
    dataType: "json",
    url: "https://maps.googleapis.com/maps/api/place/search/json?location=40.47,-73.58&radius=5000&sensor=false&key=MYOWN&name&callback=?",
    success: function(data) {
        console.log('success');
    },
    error: function(data) {
        console.log('error');
    }
});

You get this error, if a server returns plain JSON. As this is a cross-site request, jQuery has to use the JSONP-technique where the server-response is interpreted as script. This is the only way to do cross-site-requests in the browser.

The problem is that the 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"});

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
  • 链接地址: http://www.djcxy.com/p/56754.html

    上一篇: 预备后要做什么?

    下一篇: Google Places API:json错误未捕获SyntaxError意外标记