我尝试使用以下 jQuery 代码从 google distancematrix API 获取 JSON 数据:
<script type="text/javascript">
$(document).ready(function(){
url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=AIzaSyC1YPi3w46cOyrkUa8s0vR9QHzeoQCoum4";
$.ajax({
type: "GET",
url: url,
dataType: "json",
jsonpCallback: "results"
})
function results(data) {
console.log("data" + data);
}
});
</script>
如果我查看浏览器 (Google Chrome) 的控制台,我会收到以下错误消息:
Uncaught SyntaxError: Unexpected token :
如果我点击该 JSON 文件,我会得到“没有可预览的内容”。
编辑:
我在我的网络选项卡中看到此回复:
奇怪的是,正确的 JSON 响应被发送到我的浏览器:
最佳答案
我认为您最终仍会遇到 CORS 问题。我建议利用 Google API 的文档以不同的方式处理它。它相当简单,为您提供更多选择并且效果更好:
(function($){
function init(){
var origin = 'Greenwich, England';
var destination = 'Stockholm, Sweden';
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING'
}, callback);
function callback(response, status) {
// See Parsing the Results for
// the basics of a callback function.
console.log(response);
}
};
$(window).ready(function(){
init();
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=yourkey">
</script>
fiddle working fiddle without key
编辑
Google 的响应将采用 JSON
或 XML
格式。要获取 JSONP
响应,Google 需要支持您的端点的该响应,但它并不支持。拥有 API key 似乎无法解决 CORS 问题,这意味着对 JSON 数据的请求将导致“不存在访问控制 header ”错误。
来自文档:“这些 Web 服务使用对特定 URL 的 HTTP 请求,将 URL 参数作为参数传递给服务。通常,这些服务以 JSON 或 XML 形式返回 HTTP 请求中的数据以进行解析和/或处理通过您的应用程序。”
关于javascript - Chrome 检测到意外 token ":",即使它不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47167164/