2012-12-14 49 views
2

所以我作出了自動完成jQuery的後一秒。 Ajax用於從遠程位置獲取沉重的xml文件。如果我搜索前。 「兩個半男人」它約有16個查詢(對於除3之外的每個字母,首先查看代碼)用ajax。執行AJAX搜索多的keydown事件

我希望它做Ajax請求第二用戶按下最後一個鍵後,所以它會做一個查詢,而不是16

所以,如果用戶按下另一個鍵之前它後的1秒,因爲最後一次keydown事件,它不會執行查詢。

<script> 
    $(document).ready(function(){ 
     $('#tv_search').keydown(function(){ 
      var search = $(this).val(); 
      if(search.length >= 3) 
      { 
       $.ajax({ 
        type: "GET", 
        url: "search.php", 
        data: {show : search, key : '890k4900k0ll' } 
       }).done(function(msg){ 
        $('#t').html(msg); 
       }); 
      } 
     }); 
    }); 
</script> 

Search for series: <input type='text' name='tv_search' id='tv_search'> 

任何想法?

+1

爲什麼你會搜索兩個半人? – BenRacicot

回答

5

你可以只使用超時,每一個鍵被按下時清除:

$(document).ready(function() { 
    $('#tv_search').on('keyup', function() { 
     clearTimeout($(this).data('timer')); 
     var search = this.value; 
     if (search.length >= 3) { 
      $(this).data('timer', setTimeout(function() { 
       $.ajax({ 
        type: "GET", 
        url: "search.php", 
        data: { 
         show: search, 
         key: '890k4900k0ll' 
        } 
       }).done(function(msg) { 
        $('#t').html(msg); 
       }); 
      }, 1000)); 
     } 
    }); 
});​ 
+0

不起作用。嘗試JSFiddle。 – bobthyasian

+0

謝謝!工作完美無瑕! Bobthyasian,它爲我工作。 –

+0

應該工作得很好,只要有一個search.php文件,並在DOM等存在正確的元素。整齊的優勢是,它不需要全局。 – adeneo

2

爲了避免在每個按鍵嘗試多個AJAX請求,產生和使用的方式setTimeout()clearTimeout()中的方法您取消最後一次超時,並在清除之後調用setTimeout()開始新的超時。 setTimeout()方法應包含在四分之一秒(250毫秒)用戶按下某個鍵後執行的AJAX請求。

我也abort()請求,如果它可用。

var timeOut = null, 
    myXHR = null; 
$(document).ready(function(){ 
    $('#tv_search').keydown(function(){ 
     // It will clear the setTimeOut activity if valid. 
     if(timeOut) clearTimeout(timeOut); 

     var search = $(this).val(); 
     if(search.length >= 3) 
     { 
      timeOut = setTimeout(function(){ 
       // Cancel the last request if valid 
       if(myXHR) myXHR.abort(); 

       myXHR = $.ajax({ 
       type: "GET", 
       url: "search.php", 
       data: {show : search, key : '890k4900k0ll' } 
       }).done(function(msg){ 
        $('#t').html(msg); 
       }); 
      }, 250);// wait for quarter second. 
     } 
    }); 
}); 
+0

http://stackoverflow.com/a/30503848/1834212 – Miguel

0

退出簡單的解決方案:

<script> 
$(document).ready(function(){ 
var mytimer; 
    $('#tv_search').keydown(function(){ 
     clearTimeout(mytimer); 
     var search = $(this).val(); 
     if(search.length >= 3) 
     { 
      mytimer = setTimeout(function(){ 
      $.ajax({ 
       type: "GET", 
       url: "search.php", 
       data: {show : search, key : '890k4900k0ll' } 
      }).done(function(msg){ 
       $('#t').html(msg); 
      }); 
     }, 1000); 
     } 
    }); 
}); 

在哪裏 'mytimer' 必須是全局變量,只需清除之前的 'mytimer' 上每一個事件的呼叫。它只會在1秒內執行最新的呼叫。