問題描述
XMLHttpRequest 無法加載 http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Affenhausen&destinations=Achenkirch&mode=driving&language=de-DE&sensor=false.請(qǐng)求的資源上不存在Access-Control-Allow-Origin"標(biāo)頭.因此,Origin 'null' 不允許訪問.
XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/distancematrix/xml?origins=Affenhausen&destinations=Achenkirch&mode=driving&language=de-DE&sensor=false. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Javascript 代碼如下
The Javascript code is as
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 可以工作,但是當(dāng)我通過瀏覽器打開它時(shí),我得到了同樣的錯(cuò)誤.
DreamWeaver works, but when I open it via a browser, I get the same error.
推薦答案
這有點(diǎn)棘手,即使你正確設(shè)置了 CORS,它仍然會(huì)失敗.您應(yīng)該使用 Google 的內(nèi)置函數(shù)來訪問它.如果您嘗試通過 $.get() 或類似方法直接訪問它,它將失敗...查看此示例:https://developers.google.com/maps/documentation/javascript/examples/distance-matrix
This is a bit tricky, even if you have CORS set up properly it still fails. You should use Google's build in functions to access it. If you try to access it directly via $.get() or similar it will fail... check this example out: https://developers.google.com/maps/documentation/javascript/examples/distance-matrix
有趣的事實(shí),當(dāng)通過 $.get() 訪問時(shí)(我不知道為什么):
Interesting fact, when accessing via $.get() (I am not sure why though):
-THIS WORKS: http://maps.googleapis.com/maps/api/geocode/
-THIS FAILS: http://maps.googleapis.com/maps/api/distancematrix/
我的建議 - 不要嘗試通過 get() 獲取 json/xml.使用 google 的 API 內(nèi)置函數(shù)發(fā)送請(qǐng)求,然后正確解析響應(yīng)
My advice - don't try fetching json/xml via get(). Use google's API build in functions to send request and then parse the response properly
此示例代碼應(yīng)該可以幫助您入門:
This example code should get you started:
// 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...
}
}
這篇關(guān)于XMLHttpRequest 無法加載,請(qǐng)求的資源上不存在“Access-Control-Allow-Origin"標(biāo)頭的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!