2017-01-25 1 views
2

Je veux définir la variable globale à partir de la fonction et la boucle ajax pour obtenir la distance. Cependant, la variable nearestIndex est toujours indéfinie.Ajax réussit en boucle pour définir la variable globale

solution d'abord, je suis arrivé était d'utiliser async: false - ce travail est dans mon navigateur pc, mais ce projet est webservice android, et cette solution fonctionne pas WebView.

Et bien sûr async: false non recommandé. J'ai besoin de cet exemple dans mon cas, j'ai cherché ce problème dans le débordement de pile, mais j'ai toujours échoué à comprendre le rappel.

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

 
function getNearest(){ 
 
\t var from = myPosition.getLatLng().lat + "," + myPosition.getLatLng().lng; 
 
\t var tempDistance; 
 
\t for(var i=0; i<allDestination.length; i++){ 
 
\t \t var destination = allDestination[i].getLatLng().lat + "," + allDestination[i].getLatLng().lng; 
 
\t \t $.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) { 
 
      \t var distance = data.distance; 
 
      \t if(i == 0){ 
 
      \t \t tempDistance = distance; 
 
      \t \t nearestIndex = i; 
 
      \t } else { 
 
      \t \t if(distance < tempDistance){ 
 
      \t \t \t tempDistance = distance; 
 
      \t \t \t nearestIndex = i; 
 
      \t \t } 
 
      \t } 
 
      } 
 
     }); 
 
\t } 
 
} 
 

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

Répondre

0

Comme vous faites affaire avec appel Async; votre code correspondant doit obtenir appelé de success gestionnaire d'appel ajax comme suit:

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

} 
+0

Merci son travail monsieur. Donc, le concept est si longueur de la longueur = 3, nous appelons la fonction de rappel 3 fois? –

+0

Bienvenue ...! son semblable: nous passons la fonction de rappel 3 fois, mais elle n'est invoquée qu'une seule fois, c'est-à-dire lors de la toute dernière exécution 'success'. – vijayP

0

que j'ai jamais eu le même problème que vous, parce que la fonction asincrounous ne peux pas retourner quoi que ce soit. donc je pense que vous devriez injecter allDestination [nearstIndex] .addTo (map); en ajax succès

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

ou vous créez fonction pour gérer ajax succès ,,, CMIIW

+0

Si j'injecte allDestination [i] .addToMap (carte) dans le succès ajax, toutes destination affichera sur la carte, je veux juste un pas tous. J'ai besoin de la distance minimale. Je ne sais pas comment créer une fonction pour gérer le succès ajax, pouvez-vous donner un exemple? –