전역 변수를 함수 및 루프 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);
}
감사합니다. 개념은 alldestination 길이가 3 인 경우 콜백 함수를 3 번 호출합니까? –
환영합니다 ...! 우리는 콜백 함수를 3 번이나 통과 시키지만, 가장 마지막의'success' 실행 시점에 한 번만 호출됩니다. – vijayP