1
我相信我對地理編碼器結果有時間問題。查看下面的代碼片段。Google地理編碼器異步問題
我基本上正在執行一個地理編碼,並得到結果。然後通過jQuery AJAX調用將結果傳遞給服務器端方法。最後,該方法的結果返回一個JSON對象。根據結果我可能會或可能不會執行第二個地理編碼。這是問題所在。
您可以看到我有一個變量hasResult
默認爲false,並且在確定有效結果時切換爲true。在所有情況下,這是完美的,除非需要第二個地理編碼。地理編碼成功發生並且代碼執行,但最後的hasResult
檢查仍然返回false。怎麼會這樣?
var hasResult = false;
geocoder.geocode({ "address": address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: results
contentType: "application/json; charset=utf-8",
success: function (result) {
if (result.Valid) {
hasResult = false;
//Some other code, works perfect
} else {
geocoder.geocode({ "address": result.ValidRequest }, function (resultsNew, statusNew) {
if (statusNew == google.maps.GeocoderStatus.OK) {
hasResult = false;
//Some other code, works perfect
}
});
}
});
});
}
});
}
});
if (hasResult == true) {
alert('Success');
} else {
alert('Fail');
}
感謝
那麼什麼你所說的是geocoder被調用,但腳本繼續到條件語句,其餘的將完成。有道理,你可以提供一個模擬你的建議嗎? – 2011-05-25 19:30:24
@Dusting我已經添加了一些原始示例來向您展示如何做到這一點。當你知道你是失敗還是成功後,執行'回調'函數(實際上是'successOrFailure'函數)。適應您的需求。對你起作用嗎? – Tadeck 2011-05-25 19:42:59
完美!有時候解決方案很簡單。 – 2011-05-25 21:03:03