XMLHttpRequest无法加载,请求的资源上没有“Access-Control-Allow-Origin”标头

XMLHttpRequest无法加载http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Affenhausen&destinations=Achenkirch&mode=driving&language=de-DE&sensor=false 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此不允许原点’null’访问。

Javascript代码是

function distanceCalc(){ start_location = $('select.start option:selected').val(); target_location = $('select.end option:selected').val(); $.get('http://maps.googleapis.com/maps/api/distancematrix/xml?origins='+start_location+'&destinations='+target_location+'&mode=driving&language=de-DE&sensor=false', function(data) { 

DreamWeaver有效,但是当我通过浏览器打开它时,我得到了同样的错误。

这有点棘手,即使你正确设置了CORS,它仍然会失败。 您应该使用Google的内置函数来访问它。 如果您尝试通过$ .get()或类似方式直接访问它,则会失败…请查看此示例: https : //developers.google.com/maps/documentation/javascript/examples/distance-matrix

有趣的事实,当通过$ .get()访问时(虽然我不知道为什么):

 -THIS WORKS: http://maps.googleapis.com/maps/api/geocode/ -THIS FAILS: http://maps.googleapis.com/maps/api/distancematrix/ 

我的建议 – 不要尝试通过get()获取json / xml。 在函数中使用google的API构建来发送请求,然后正确解析响应

这个示例代码可以帮助您入门:

 // var origins = []; // var destinations = []; var distanceMatrix = new google.maps.DistanceMatrixService(); var distanceRequest = { origins: origins, destinations: destinations, travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false }; distanceMatrix.getDistanceMatrix(distanceRequest, function(response, status) { if (status != google.maps.DistanceMatrixStatus.OK) { alert('Error was: ' + status); } else { var origins = response.originAddresses; var destinations = response.destinationAddresses; // rest of your code here... } } 

听起来你有一个跨域问题,因为响应中没有’Access-Control-Allow-Origin’标头。 如果不是这种情况,浏览器通常不允许请求位于另一个域上的服务而不是触发请求的javascript。

看起来像你正在使用的api不适用于这种方法,也许这可以帮助: 如何对Google Maps API进行跨域AJAX调用?

您似乎正在尝试从您的域中访问其他域。 它是一个跨域问题,对于这种跨域访问,不允许使用json调用或服务器端调用。

如果你使用像我这样的angularjs请求应该是这样的

 var req = { method:'GET', 'url:'https://maps.googleapis.com/maps/api/distancematrix/json', headers: { 'Access-Control-Allow-Origin': '*' }, params: { origins:attrs.from, destinations:attrs.to } };