2017-01-25 3 views
2

전역 변수를 함수 및 루프 ajax로 설정하여 거리를 가져 오려고합니다. nearestIndex 변수는 항상 정의되지 않습니다.Ajax에서 루프를 완료하여 전역 변수를 설정하십시오.

첫 번째 해결책은 비동기를 사용하는 것입니다. false 이것은 내 PC 브라우저에서 작동하지만이 프로젝트는 안드로이드에 webservice이며이 솔루션은 webview에서 작동하지 않습니다.

그리고 물론 비동기 : 거짓 권장하지 않습니다. 내 경우에는이 예제가 필요하다. 스택 오버플로에서이 문제를 찾고 있었지만 항상 콜백에 대해서는 이해하지 못했다. asincrounous 기능이 아무것도 반환하지 못할 그것 때문에

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

답변

0

는 비동기 호출을 처리되기 때문에, 내가 allDestination를 주입하면

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

감사합니다. 개념은 alldestination 길이가 3 인 경우 콜백 함수를 3 번 ​​호출합니까? –

+0

환영합니다 ...! 우리는 콜백 함수를 3 번이나 통과 시키지만, 가장 마지막의'success' 실행 시점에 한 번만 호출됩니다. – vijayP

0

나는 지금, 당신처럼 같은 문제를 가지고있다. 그래서 나는 당신이 allestestination [nearstIndex]를 주사한다고 생각합니다. addTo (map); 아약스의 성공에

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

또는 아약스의 성공을 처리하는 함수를 만들 ,,, CMIIW

+0

는 [내가] .addToMap 아약스 성공 (지도), 목적지의 모든지도에 표시됩니다, 난 그냥 하나를 원하는 : 다음과 같이 관련 코드는 Ajax 호출의 success 핸들러에서 호출되는합니다 그들 전부는 아닙니다. 최소한의 거리가 필요해. 내가 아약스 succes 처리하는 함수를 만드는 방법을 몰라, 당신은 몇 가지 예를 들어 줄 수 있습니까? –