2012-07-03 3 views
7

AJAX 요청을 지연하여 입력 셀의 마지막 키 업 이후 2-3 초 내에 전송하려고합니다.
지금까지 요청을 지연시킬 수 있었지만 2 ~ 3 초 후에는 필드의 모든 키 입력에 대해 하나의 요청을 보냈습니다 ...
어떻게 jQuery를 취소하고 첫 번째 키 업을 보낼 수 있습니까?
다음은 지금까지의 코드입니다 : 위의jQuery AJAX 요청에 지연을 추가하려고 시도했습니다.

$('#lastname').focus(function(){ 
      $('.terms :input').val(""); //clears other search fields 
}).keyup(function(){ 
    caps(this); //another function that capitalizes the field 
    $type = $(this).attr("id"); // just passing the type of desired search to the php file 
     setTimeout(function(){ // setting the delay for each keypress 
       ajaxSearchRequest($type); //runs the ajax request 

     }, 1000); 
}); 

이 코드는, 다음 1 초를 기다립니다 키 누름에 따라 4-5 AJAX 요청을 보냅니다. 난 단지 하나를 마지막으로 보낸 후 keyup
StackOverflow에서 Javascript를 사용하는 몇 가지 유사한 솔루션을 찾았지만 프로그래밍에 대한 나의 작은 지식으로 인해이를 프로젝트에 구현할 수 없었습니다. 당신이 할 수 있도록,

function ajaxSearchRequest($type){ 
       var ajaxRequest2; // The variable that makes Ajax possible! 

       try{ 
        // Opera 8.0+, Firefox, Safari 
        ajaxRequest2 = new XMLHttpRequest(); 
       }catch (e){ 
        // Internet Explorer Browsers 
        try{ 
        ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP"); 
        }catch (e) { 
        try{ 
        ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP"); 
        }catch (e){ 
        // Something went wrong 
        alert("Browser error!"); 
        return false; 
        } 
        } 
       } 

       ajaxRequest2.onreadystatechange = function(){ 
        if(ajaxRequest2.readyState == 4){ 

         $result = ajaxRequest2.responseText; 
         $('#resultcontainer').html($result); 

        }} 


       var searchterm = document.getElementById($type).value; 


       var queryString ="?searchterm=" + searchterm +"&type=" +$type; 


       if(searchterm !== ""){ 

       ajaxRequest2.open("GET", "searchrequest.php" + 
           queryString, true); 
       ajaxRequest2.send(null); 
       } 
     } 
+0

'ajaxSearchRequest' 코드를 게시하십시오 – Imdad

+0

@Imdad 왜 그게 필요한가요? 이전의 키 업을 취소하지 않고 각 키 업이 새로운 시간 초과를 이미 볼 수 있습니다. – Esailija

+0

다른 해결 방법이 있습니다. 나는 함수가 무엇인지 알 수 있는지 만 알 수있다. – Imdad

답변

15

저장 변수에 타임 아웃 :

[SOLVED] 최종 작업 코드, @ Dr.Molle 덕분에 : 여기

$('#lastname').focus(function(){ 
      $('.terms :input').val(""); 
}).keyup(function(){ 
    caps(this); 
    $type = $(this).attr("id"); 

    window.timer=setTimeout(function(){ // setting the delay for each keypress 
      ajaxSearchRequest($type); //runs the ajax request 

     }, 3000); 

}).keydown(function(){clearTimeout(window.timer);}); 

ajaxSearchRequest 코드입니다 최근 시간 제한을 지우는 방법 :

clearTimeout(window.timer); 
window.timer=setTimeout(function(){ // setting the delay for each keypress 
       ajaxSearchRequest($type); //runs the ajax request 

     }, 3000); 
+0

전역 변수에 그 값을 저장하지 않고 할 때 +1 할 것입니다 ... – Alnitak

+0

어디에 저장 하시겠습니까? –

+0

클로저를 사용할 수 있습니다. – Christoph

-2

나는 Molle 's swer하지만 더 성능

이 변경 아약스 요청을가는상의를 중단하고 새로운 요청을 보내드립니다
var ajaxRequest2; // The variable that makes Ajax possible! 
function getAjaxObject() 
{ 
       try{ 
        // Opera 8.0+, Firefox, Safari 
        ajaxRequest2 = new XMLHttpRequest(); 
       }catch (e){ 
        // Internet Explorer Browsers 
        try{ 
        ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP"); 
        }catch (e) { 
        try{ 
        ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP"); 
        }catch (e){ 
        // Something went wrong 
        alert("Browser error!"); 
        // return false; 
        } 
        } 
       } 
    return ajaxRequest2; 


} 
    getAjaxObject(); 

    function ajaxSearchRequest($type){ 



       if(typeof ajaxRequest2 =="undefined" || ajaxRequest2 == false) 
       { 
        return; 
       } 
       ajaxRequest2.abort(); 

       ajaxRequest2.onreadystatechange = function(){ 
        if(ajaxRequest2.readyState == 4){ 

         $result = ajaxRequest2.responseText; 
         $('#resultcontainer').html($result); 

        }} 


       var searchterm = document.getElementById($type).value; 


       var queryString ="?searchterm=" + searchterm +"&type=" +$type; 


       if(searchterm !== ""){ 

       ajaxRequest2.open("GET", "searchrequest.php" + 
           queryString, true); 
       ajaxRequest2.send(null); 
       } 
     } 

을 향상시킬 것입니다. 당신이

Typed-이> 기다렸다 때 도움이됩니다 4 초 -> 요청 전송 -> (응답하지받은)를 다시 입력 -> 기다렸다 4 2 ~> 다른 요청은 화재라고 당신이 할하려는

+0

내가 downvoted 이유를 알 수 있습니까? – Imdad

+0

그것은 나쁜 대답이기 때문에? 중단 요청은 도움이되지 않습니다 - 서버 (대개)는 쿼리 처리를 계속합니다. 올바른 수정은 요청을 계속 보내지 않는 것입니다. – Alnitak

+0

하지만 네트워크 오버 헤드를 줄입니다. 그리고 타이핑 속도가 약간 느리면 여러 응답을받는 문제를 해결합니다. – Imdad

3

디 바운싱.

여기에 Ben Alman의 jquery plugin이 있습니다.

그리고 underscore.js도이 기능을 포함합니다.

실제로 아약스 요청 시스템을 해킹 할 필요가 없습니다. 올바른 순간에 전화가 왔는지 확인하십시오.

+0

불량 검사, 고맙습니다. – krasatos

관련 문제