Javascript XMLHttpRequest无法加载,否';访问控制允许原点';请求的资源上存在标头
无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“null” Javascript代码如下所示Javascript XMLHttpRequest无法加载,否';访问控制允许原点';请求的资源上存在标头,javascript,jquery,xmlhttprequest,Javascript,Jquery,Xmlhttprequest,无法加载XMLHttpRequest。请求的资源上不存在“Access Control Allow Origin”标头。因此,不允许访问源“null” Javascript代码如下所示 function distanceCalc(){ start_location = $('select.start option:selected').val(); target_location = $('select.end option:selected').val(); $.get
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可以工作,但当我通过浏览器打开它时,会出现相同的错误。听起来像是您遇到了跨域问题,因为响应中没有“Access Control Allow Origin”标题。如果不是这种情况,浏览器通常不允许请求位于触发请求的javascript之外的另一个域上的服务 您使用的api似乎不适用于此方法,也许这有助于:
您似乎正在尝试从您的域访问其他域。这是一个跨域问题,无论您使用json调用还是服务器端调用,都不允许使用ajax进行跨域访问。这有点棘手,即使您正确设置了CORS,它仍然会失败。你应该使用谷歌的内置函数来访问它。如果您试图通过$.get()或类似方式直接访问它,它将失败。。。请查看此示例: 有趣的事实是,当通过$.get()访问时(我不知道为什么): 我的建议-不要尝试通过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...
}
}
如果你像我一样使用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 }
};
我在本地遇到了这个错误,不,绝对不应该。Access Control Allow Origin是一个响应头,您不能从客户端添加它。此外,问题中的代码是jQuery,问题上的标记是jQuery;他们没有使用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 }
};