[英]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.