同一个AJAX调用的成功和错误

时间:2017-05-13 21:50:25

标签: javascript json ajax google-distancematrix-api

在写这个标题之前,我曾三思而后行,但事实就是如此。这个问题与DistanceMatrix AJAX query on Google directions Service route returns error有关,但我设法取得了成功。在MVC视图中单击输入时会触发该事件:

<input onclick="initMap()">

然后,在.js文件中使用路径启动地图的方法:

var map;
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
});
directionsDisplay.setMap(map);
directionsService.route({
    origin: "Lisbon",
    destination: "Porto",
    travelMode: 'DRIVING'
}, function (response, status) {
    if (status === 'OK') {
        directionsDisplay.setDirections(response);
        $.ajax({
            url: "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Washington,DC&destinations=New+York+City,NY&key=AIzaSyAuEZxHZusVYyvsDUk8USfi2blK42c5oSo",
            success: alert("success"),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown != 'abort') alert("error");
            },
        })
    } else {
        window.alert('Directions request failed due to ' + status);
    }
 });
}

当我点击输入时,会显示地图(尚未选择路线),弹出&#34;成功&#34;。你点击它,还有另一个&#34;错误&#34;弹出,你点击,最后你看到路线(里斯本 - &>波尔图),应该是。

initMap()只调用一次,断点显示AJAX只被调用一次。

STRANGE NOTE :如果我将dataType: JSON添加到AJAX通话中,我会获得&#34;成功&#34;警告并在单击警报后出现Visual Studio错误:

Unhandled exception at line 4, column 11992 in http://localhost:31620/Scripts/jquery-3.1.1.min.js //note is a jQuery error
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'toLowerCase'

所以,我的问题是,这里发生了什么,以及如何在directionsService.route上获得DistanceMatrix JSON(简言之,在设置路线后获取路线数据)。

0 个答案:

没有答案