我相信我有一个地理编码器结果的时间问题。请参阅下面的代码片段。
我基本上是在执行地理编码并获得结果。然后,我通过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');
}谢谢
发布于 2011-05-26 03:28:51
这是因为您在从服务器获取结果之前检查了hasResult的值。之所以会发生这种情况,是因为请求是异步的。你应该使用回调来代替。
编辑:
试试这个(这只是一个原型,没有经过测试,更改它以提高可读性,将successOrFailure作为参数/回调传递,等等):
var hasResult = false;
var successOrFailure = function(hasResult){
if (hasResult == true) {
alert('Success');
} else {
alert('Fail');
}
};
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;
successOrFailure(hasResult);
//Some other code, works perfect
} else {
geocoder.geocode({ "address": result.ValidRequest }, function (resultsNew, statusNew) {
if (statusNew == google.maps.GeocoderStatus.OK) {
hasResult = false;
successOrFailure(hasResult);
//Some other code, works perfect
}
});
}
});
});
}
});
}
});https://stackoverflow.com/questions/6129733
复制相似问题