JS

2009-12-08 4 views
0

에서 콜백와 지역 변수를 조작 여기에 jQuery로 내 코드입니다 : 응답JS

function check_hotel_exists(value, col) 
{ 
     var url = base_url + 'ajax/checkuniquehotel'; 

     var response = false; 

     $.get(url, {hotelname:value}, function(data){ 
      if (data === 'true') response = true; 
     }); 

     alert((response) ? 'Hotel is Not Existing' : 'Hotel Exists'); 

     return [response, "That hotel already exists"]; 
} 

값은 변경되지 않습니다.

get 함수에서 콜백으로 응답 값을 변경하려면 어떻게해야합니까? 'true'또는 'false'인 서버 응답에서 변수 데이터를 기대합니다.

어떤 도움

을 감상 할 수있다. :

답변

3

check_hotel_exists 기능을 종료 한 후 true로 응답을 설정하도록되어 아약스 콜백이 비동기 적으로 실행하기 때문에이 값은 변경하지 않습니다. 가능한 해결 방법은 async 옵션을 false으로 설정하여 동 기적으로 ajax 요청을 실행하는 것입니다.

$.ajax({ 
    url: base_url + 'ajax/checkuniquehotel', 
    async: false, 
    data: { hotelname: value }, 
    success: function(result) { 
     if (result === 'true') response = true; 
    } 
}); 

더 이상 값을 반환해야하는 함수, 또 다른 해결 방법은 비동기 호출을 수행 할 수 있지만이 경우에는 모든 작업이 success 콜백에서 수행되어야한다 (예를 들어,이 호텔은 경우 오류 메시지가 표시되지 이름은 성공 콜백에 이미 있습니다.) IMHO 더 나은 접근 방법입니다.

0

모든 ajax 요청은 비동기식이므로 ajax 호출 결과에 따라 무언가를 리턴하는 함수를 작성할 수 없습니다. (예 : AJAX 호출이 완료된 후 페이지에 텍스트의 일부를 변경) : 당신은 비동기 응답을 처리해야

function check_hotel_exists(value, col) 
{ 
    var url = base_url + 'ajax/checkuniquehotel'; 

    $.get(url, {hotelname:value}, function(data){ 
     var msg = (data === 'true') ? 'Hotel is Not Existing' : 'Hotel Exists'; 

     $("#resultmsg").text(response); 
    }); 
} 
0

function check_hotel_exists(value, col) 
{ 
     var url = base_url + 'ajax/checkuniquehotel'; 

     var response = false; 

     $.get(url, {hotelname:value}, function(data){ 
      if (data === 'true') response = true; 
      alert((response) ? 'Hotel is Not Existing' : 'Hotel Exists'); 
      //this wont work, so do something else!!!! 
      //return [response, "That hotel already exists"]; 
     }); 
} 
-1

더러운 접근 방식을 시도,하지만 작동합니다

은 당신의 변수는 콜백 함수 밖에서 정의 :

var response = false; 

function check_hotel_exists(value, col) 
{ 
     var url = base_url + 'ajax/checkuniquehotel'; 

     response = false; 

     $.get(url, {hotelname:value}, function(data){ 
      if (data === 'true') response = true; 
     }); 

     alert((response) ? 'Hotel is Not Existing' : 'Hotel Exists'); 

     return [response, "That hotel already exists"]; 
} 
+0

이 아무튼를 콜백 매개 변수로 수신 기능, 즉 그 차례에 check_hotel_exists 기능 비동기 일하지 마라. Ajax 호출은 비동기식입니다. –

+0

이것은 확실히 작동하지 않습니다. – Rippo

0

해결책을하게하는 것입니다 귀하의

function check_hotel_exists(value, col, callback) 
{ 
     var url = base_url + 'ajax/checkuniquehotel'; 

     var response = false; 

     $.get(url, {hotelname:value}, function(data){ 
      if (data === 'true') response = true; 
      if (callback) {callback.call(response);} 
     }); 
} 

이 같은 호텔의 존재를 확인하여 원하는 목적지 당신이 그것을 호출 할 수있는이 방법 :

check_hotel_exists(value, col, function(response){ 
    alert(response); 
});