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

标签 javascript jquery ajax android-webservice

我想从函数中设置全局变量并循环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/

相关文章:

javascript - 单击后CSS下拉菜单不关闭

javascript - 为密码字段输入默认文本

javascript - Angular 不允许我将表达式放入 <timer> 元素属性中

javascript - 使按下的按键只注册一次而不是连续注册

php - 带有 PHP 文件的 JQuery AJAX 缓存

javascript - jQuery/JavaScript : Autopopulate Dynamically Populated Elements

JavaScript 函数 Array.prototype.includes() 在 for 循环中不起作用

javascript - Ajax 调用以 Base64 字符串形式返回 PDF 文件

php - Laravel 5.3,用图像替换分页链接(<< 和 >>)

jquery - 使用 jQuery 读取 xml