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

时间:2017-01-25 05:27:48

标签: javascript jquery ajax android-webservice

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

我得到的第一个解决方案是使用 async:false - 这可以在我的电脑浏览器中使用,但是这个项目是web服务到android,这个解决方案对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);
}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

我遇到过和你一样的问题, 因为asincrounous函数不能返回任何东西。 所以我认为你应该注入allDestination [nearstIndex] .addTo(map);进入ajax成功

if(i == 0){
                tempDistance = distance;
                allDestination[i].addTo(map);
            } else {
                if(distance < tempDistance){
                    tempDistance = distance;
                    allDestination[i].addTo(map);
                }
            }

或者你创建了处理ajax成功的函数,,, CMIIW

答案 1 :(得分:0)

正在处理异步调用;您的相关代码必须从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);
      });
  }

}