Google Places API:json错误未捕获的SyntaxError意外的令牌 [英] Google Places API: json error Uncaught SyntaxError Unexpected token

查看:97
本文介绍了Google Places API:json错误未捕获的SyntaxError意外的令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 :"

为什么地狱就是它?
我认为谷歌做对了,他们的json必须是正确的...那么问题出在哪里?

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

这是我的代码

$.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');
    }
});


推荐答案

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

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.

问题是服务器必须支持JSONP 和环绕JSON回答了jQuery生成的回调。响应必须如下:

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"});

服务器 - PHP示例:

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.");";

客户端 - jQuery示例:

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>

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


  • HTTP-Request to a JSON source

  • 将JSON包装为回调函数

这篇关于Google Places API:json错误未捕获的SyntaxError意外的令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆