Google Places API:json错误未捕获的SyntaxError意外的令牌

Fra*_*sco 8 javascript ajax jquery json

我不明白为什么我会得到这么多不同的错误.我正在使用Google Places API进行测试,并且只使用带回调的ajax查询调用,我收到了json,但是在CHrome浏览器中,我得到了

"Uncaught SyntaxError: Unexpected token :"
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我认为谷歌做对了,他们的json必须是正确的......所以问题出在哪里?

这是我的代码

$.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');
    }
});
Run Code Online (Sandbox Code Playgroud)

Til*_*zer 4

如果服务器返回纯 JSON,您会收到此错误。由于这是跨站点请求,jQuery 必须使用 JSONP 技术,其中服务器响应被解释为脚本。这是在浏览器中执行跨站点请求的唯一方法。

问题是服务器必须支持 JSONP并用 jQuery 生成的回调包围 JSON 答案。响应必须如下所示:

jQuery17101705844928510487_1324249734338({"data":"whatever"});
Run Code Online (Sandbox Code Playgroud)

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.");";
Run Code Online (Sandbox Code Playgroud)

使用 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>
Run Code Online (Sandbox Code Playgroud)

您可以将 PHP 代码替换为任何其他服务器平台并执行所需的步骤。

  • 对 JSON 源的 HTTP 请求
  • 将 JSON 包装为回调函数