2011-01-12 3 views
2

Google지도 API를 사용하여 작은 앱을 만들고 있습니다. 텍스트 상자에 type 핀을 넣으면 AJAX 호출이 시작되어 데이터베이스에서 좌표를 가져옵니다. keyup 이벤트에 대한 작업을 호출하고 2자를 텍스트 상자에 넣은 후 문제는 AJAX 호출을 시작하기 전에 사용자가 모든 것을 입력 할 수있게하려는 것입니다. Asynch를 false로 설정하면 비동기 호출이지도에서 마커를 제거하지 못하게되고 마커가 모두 사라지기 전에 더 많은 마커를 가져옵니다.jQuery에서 keyup 이벤트 ajax 요청을하기 전에 몇 밀리 초를 유지하는 방법

$('input[name="location"]').keyup(function(){ 
     if($(this).val().length > 1){ 
      $(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right'); 
      deleteOverlays(); 
      $.ajax({ 
       dataType: "json", 
       url: "locAjax.php", 
       data: ({term : this.value}), 
       async: false, 
       type: "GET", 
       success: function(data) { 
        setMarkers(map, data); 
       } 
      }); 
      $(this).css('background', '#fff'); 
     } 
    }); 

전화를 걸기 전에 어떤 종류의 시간 초과를 사용하여 전체 시간을 쓸 수 있습니다. 또는 적어도 그것의 절반.

알려 주시기 바랍니다.

고마워요.

답변

3
var timer; 

$('input[name="location"]').keyup(function(){ 
    clearTimeout(timer); 
    timer = setTimeout(function(){ 
    if($(this).val().length > 1){ 
     $(this).css('background', '#fff url("/images/indicator.gif") no-repeat center right'); 
     deleteOverlays(); 
     $.ajax({ 
      dataType: "json", 
      url: "locAjax.php", 
      data: ({term : this.value}), 
      async: false, 
      type: "GET", 
      success: function(data) { 
       setMarkers(map, data); 
      } 
     }); 
     $(this).css('background', '#fff'); 
    } 
    }, 5000); // <--- do ajax call after 5 seconds of the last keyup character... 
}); 
+0

정말 고마워요. 그것은 완벽하게 작동했습니다. – Aayush

1

매우 간단합니다. setTimeout과 clearTimeout을 사용해야합니다. 예 :

var timerId = null; 
$('input[name="location"]').keyup(function(){ 
    if (timerId) { 
     clearTimeout(timerId); 
    } 
    timerId = setTimeout(makeServiceCall, 20); // wait for 20 millisecond. 
}); 

여기서 makeServiceCall은 서비스 호출을 위해 사용자가 윤곽을 그리는 코드입니다. 이 함수는 또한 timerId를 null로 재설정해야합니다. 그래서 키를 누를 때마다 타이머가 서비스 호출을 시작하도록 설정합니다. 타임 아웃이 발생하기 전에 키를 누르면 이전 타이머가 재설정되고 새로운 타이머가 설정됩니다.

관련 문제