/ / XDomainRequest onLoad sa nespúšťa správne v IE8 - ajax, google-maps, internet-explorer-8, xdomainrequest, xdr

XDomainRequest onLoad nespúšťa správne v IE8 - ajax, google-maps, internet-explorer-8, xdomainrequest, xdr

Vypúšťam požiadavku na rozhranie Google geocode API, aby som získal zemepisnú šírku a dĺžku daného PSČ. Funguje to dobre vo všetkých prehľadávacích pruhoch IE8 (šok!).

Aby som to obišiel, implementoval som XDomainRequest pre IE.

  /*
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];
}

a takto to nazývam

applicantPostcode = fm.find("input[name=postcode]").val(),
applicantPostcodeCoords = convertPostcodeToLatLng(applicantPostcode);

Pred pokračovaním tiež skontrolujem chyby

if (applicantPostcodeCoords[0] === "error") {
$("#sb-player #postcode").after("<label class="invalid-postcode">" + applicantPostcodeCoords[1] + "</label>");

return;
}

Teraz hovorím, že to nefunguje, to je lož, funguje to, nefunguje to okamžite, takže chyba sa vyhodí, keď to už nebude.

Skúšal som ladenie v IE8 a zdá sa, že to robí

  • získať PSČ z prvku formulára
  • skočiť na funkciu s PSČ
  • vytvoriť nový XDomainRequuest
  • preskočiť xdr.onload
  • vytvoriť nový XDomainRequest
  • skočte z podmieneného a dole na isPostcodeValid a vráťte chybu

Teraz požiadavka funguje, testoval som ju, problém je, že nefunguje okamžite, a preto skočí do omylu.

Ktokoľvek získal prehľad o tom, prečo skáče skôr cez zaťaženie než do neho?

Vďaka!

odpovede:

0 pre odpoveď č. 1

Akonáhle sa vaša funkcia načíta, ide do prvej podmienky a zlyháva

   if (postcode.match(postcodeRegex) && response.status === "OK") {
lat = response.results[0].geometry.location.lat;
lng = response.results[0].geometry.location.lng;

isPostcodeValid = true;
}

keďže neexistuje odpoveď zatiaľ ste v tejto chvíli neposlali žiadosť?

Takže keď narazíte na toto pri prvom spustení funkcie, if (!isPostcodeValid) return ["error", "Please enter a valid postcode"];