gpt4 book ai didi

javascript - Ajax 在循环中成功设置全局变量

转载 作者:行者123 更新时间:2023-12-01 05:23:03 25 4
gpt4 key购买 nike

我想从函数中设置全局变量并循环ajax来获取距离。但是,nearestIndex 变量始终未定义。

我得到的第一个解决方案是使用async: false - 这在我的电脑浏览器中可以工作,但是这个项目是针对android的webservice,并且这个解决方案不适用于webview。

当然不推荐async: false。我的例子需要这个例子,我一直在堆栈溢出中寻找这个问题,但我总是无法理解回调。

var allDestination = ["A", "B", "C"];
var nearestIndex;

function getNearest(){
var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;
var tempDistance;
for(var i=0; i<allDestination.length; i++){
var destination = allDestination[i].getLatLng().lat + "," + allDestination[i].getLatLng().lng;
$.ajax({
type: "GET",
url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
dataType: 'json',
contentType: "application/json",
success: function (data) {
var distance = data.distance;
if(i == 0){
tempDistance = distance;
nearestIndex = i;
} else {
if(distance < tempDistance){
tempDistance = distance;
nearestIndex = i;
}
}
}
});
}
}

function onMapClick(e) {
myPosition.setLatLng(e.latlng);
myPosition.addTo(map);
getNearest();
allDestination[nearestIndex].addTo(map);
}

最佳答案

当您处理异步调用时;您的相关代码必须从 ajax 调用的 success 处理程序中调用,如下所示:

var allDestination = ["A", "B", "C"];
var nearestIndex;
var tempDistance;
var successReceived = 0; //counter to keep watch on ajax success callback

//modify the function signature to receive index as well as callback function
function getNearest(index, callbackFunction) {
var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng;

var destination = allDestination[index].getLatLng().lat + "," + allDestination[index].getLatLng().lng;
$.ajax({
type: "GET",
url: "http://localhost:8989/route?point=" + from + "&point=" + destination + "&points_encoded=false&instructions=false",
dataType: 'json',
contentType: "application/json",
success: function(data) {
successReceived++; //increment the success counter
var distance = data.distance;
if (index == 0) {
tempDistance = distance;
nearestIndex = index;
} else {
if (distance < tempDistance) {
tempDistance = distance;
nearestIndex = index;
}
}

//check if we got all the ajax response back. If yes then call the callback function
if(successReceived == allDestination.length && typeof callbackFunction == 'function')
{
callbackFunction();
}
}
});

}

function onMapClick(e) {
myPosition.setLatLng(e.latlng);
myPosition.addTo(map);

for (var i = 0; i < allDestination.length; i++) {
//pass the current index and callback function
getNearest(i,function(){
allDestination[nearestIndex].addTo(map);
});
}

}

关于javascript - Ajax 在循环中成功设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com