“ SyntaxError:意外令牌':'。解析错误。” JSON&ajax

问题描述 投票:1回答:1

我正在尝试将Google Maps api与距离矩阵api一起使用,我以json格式获取路线以及距离和时间。

我从以下位置获取数据的链接示例:

https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:ChIJ7-bxRDmr3oARawtVV_lGLtw&destinations=place_id:ChIJyYB_SZVU2YARR-I1Jjf08F0&key=YOUR_API_KEY&units=imperial

并且数据如下查看:

{
   "destination_addresses" : [ "2920 Zoo Dr, San Diego, CA 92101, USA" ],
   "origin_addresses" : [
      "San Diego International Airport (SAN), 3225 N Harbor Dr, San Diego, CA 92101, USA"
   ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "5.2 mi",
                  "value" : 8440
               },
               "duration" : {
                  "text" : "13 mins",
                  "value" : 756
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

我在按钮单击(ajax)上调用jquery函数,如下所示:

$.ajax({
        type: 'GET',
        url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:' + me.originPlaceId + "&destinations=place_id:" + me.destinationPlaceId + "&key=YOUR_API_KEY&units=imperial",
        dataType: "JSONP", // data type expected from server
        accepts: 'application/json',
        success: function(data) {
          console.log(data);
        },
        error: function(error) {
          console.log('Error: ' + error);
        }
});

此代码是许多其他帖子的结果,但我仍然收到错误:

SyntaxError: Unexpected token ':'. Parse error.

在json数据的第2行中。Safari浏览器上会发生此错误,如果我在chrome上运行代码,则会收到以下错误:

jquery-3.4.1.min.js:2 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://maps.googleapis.com/maps/api/distancematrix/json?origins=place_id:ChIJ7-bxRDmr3oARawtVV_lGLtw&destinations=place_id:ChIJyYB_SZVU2YARR-I1Jjf08F0&key=AYOUR_API_KEY&units=imperial&callback=jQuery34106919863879807548_1566930061936&_=1566930061937 with MIME type application/json.

我需要帮助解决这些错误,在此先谢谢您。

javascript jquery json ajax google-distancematrix-api
1个回答
0
投票

由于您在client-side(前端)中创建了Distance Matrix API web service request,这就是为什么您会收到跨域阻止错误(CORB)的原因。 Web服务请求应在服务器端。]中执行。

[请注意,如果您打算在客户端使用Distance Matrix,则JavaScript API具有Distance Matrix服务(可防止CORB问题)。请参考此指南:https://developers.google.com/maps/documentation/javascript/distancematrix

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.