[英]XDomainRequest onLoad not firing correctly in IE8
我向Google地理编码api发出请求,以获取给定邮政编码的纬度和经度。 在所有浏览器中,IE8都可以正常工作(震撼!)。
为了解决这个问题,我已经为IE实现了XDomainRequest。
/*
Convert postcode to lat/lng.
*/
var convertPostcodeToLatLng = function(postcode) {
var isPostcodeValid = false,
postcodeRegex = /[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}/gi,
lat,
lng;
if (window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.onload = function() {
response = JSON.parse(xdr.responseText);
if (postcode.match(postcodeRegex) && response.status === 'OK') {
lat = response.results[0].geometry.location.lat;
lng = response.results[0].geometry.location.lng;
isPostcodeValid = true;
}
}
} else {
$.ajax({
url: '//maps.googleapis.com/maps/api/geocode/json?address=' + postcode + ',+UK&sensor=false',
type: 'get',
dataType: 'json',
cache: false,
async: false,
success: function(response) {
window.console && console.log(response);
if (postcode.match(postcodeRegex) && response.status === 'OK') {
lat = response.results[0].geometry.location.lat;
lng = response.results[0].geometry.location.lng;
isPostcodeValid = true;
}
},
error: function(response) {
// error
}
});
}
if (!isPostcodeValid) return ['error', 'Please enter a valid postcode'];
return [lat, lng];
}
这就是我的称呼方式
applicantPostcode = fm.find('input[name=postcode]').val(),
applicantPostcodeCoords = convertPostcodeToLatLng(applicantPostcode);
我还要检查错误,然后再继续
if (applicantPostcodeCoords[0] === 'error') {
$('#sb-player #postcode').after('<label class="invalid-postcode">' + applicantPostcodeCoords[1] + '</label>');
return;
}
现在我说这行不通,这是一个谎言,它确实行之有效,只是行不通,所以错误在不应该发生时会被触发。
我已经尝试在IE8中调试,这似乎是在做
现在,该请求确实有效,我已经对其进行了测试,问题在于它无法立即正常工作,因此跳入了错误。
任何人都了解为什么它会跳过负载而不是进入负载?
谢谢!
一旦函数加载,它将进入第一个条件并失败
if (postcode.match(postcodeRegex) && response.status === 'OK') {
lat = response.results[0].geometry.location.lat;
lng = response.results[0].geometry.location.lng;
isPostcodeValid = true;
}
因为您还没有发送请求,目前还没有响应 ?
因此,当您在函数的第一次运行中点击此命令时, if (!isPostcodeValid) return ['error', 'Please enter a valid postcode'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.