简体   繁体   English

Ajax成功循环设置全局变量

[英]Ajax succes in loop to set global variable

I want to set global variable from function and loop ajax to get distance. 我想从函数设置全局变量并循环ajax以获取距离。 However the nearestIndex variable is always undefined. 但是, 最近索引变量始终未定义。

First solution I got was to use async: false - this is work in my pc browser, but this project is webservice to android, and this solution not work to webview. 我得到的第一个解决方案是使用async:false-这可以在我的PC浏览器中使用,但是此项目是android的web服务,而该解决方案不适用于webview。

And of course async: false not recommended. 当然是异步的:不推荐使用false I need this example in my case, I've been looking for this problem in stack overflow, but i always failed to understand about callback. 在我的情况下,我需要这个示例,我一直在堆栈溢出中寻找此问题,但是我始终无法理解回调。

 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); } 

I ever have got the same problem like you, it because asincrounous function cant return anything. 我曾经遇到过像您一样的问题,这是因为非函数无法返回任何内容。 so I think you shoud inject allDestination[nearstIndex].addTo(map); 所以我认为您应该注入allDestination [nearstIndex] .addTo(map); into ajax success 进入ajax成功

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

or you create function to handle ajax success,,, CMIIW 或者您创建函数来处理Ajax成功,CMIIW

As you are dealing with Async call; 当您处理异步调用时; your relevant code has to get called from success handler of ajax call as follows: 您必须从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);
      });
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM