簡體   English   中英

jQuery 搜索欄實時更新

[英]jQuery search bar live update

我正在嘗試制作一個搜索欄,用於更新在數據庫中找到的項目列表,這些項目類似於此搜索欄的值。 這是我的酒吧代碼:

$(document).ready(function(){
    $('#search').keyup(function () {
        $('#results').html('');

        let searchValue = $(this).val();

        if(searchValue !== ''){
            $.ajax({
                type: 'GET',
                url: '../controller/searchItem.php',
                data: 'data=' + encodeURIComponent(searchValue),
                success: function(data){
                    if(data !== ""){
                        $('#results').append(data);
                    }else{
                        document.getElementById('results').innerHTML = "<div style='font-size: 20px; text-align: center; margin-top: 10px'><p>Oups, ce que vous cherchez n'existe pas encore !</p></div>";
                    }
                }
            })
        }
    })
});

但實際上當我在做 Shift+Letter 時,它會因為“.keyup”而發送兩個請求。 我只想用這種組合發送一個請求,而不必失去對搜索欄的關注或必須按 Enter(換句話說,動態)。

有人對我的問題有什么建議嗎? 提前謝謝了 !

在 keyup 上發送 ajax 請求並不是很聰明。 為什么? 因為我可以向我的鍵盤發送 1000 次垃圾郵件,它會發送 1000 個請求。 您可能想要做的是在用戶完成輸入后發送請求。

var typingTimer;
var doneTypingInterval = 1000; // Trigger the request 1 second/1000 ms after user done typing.
var input = $('#input'); // Your input

input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

input.on('keydown', function () {
  clearTimeout(typingTimer);
});

// user is done, send ajax request.
function doneTyping () {
   let searchValue = $('#input').val();

   if(searchValue !== ''){
            $.ajax({
                type: 'GET',
                url: '../controller/searchItem.php',
                data: 'data=' + encodeURIComponent(searchValue),
                success: function(data){
                    if(data !== ""){
                        $('#results').append(data);
                    }else{
                        document.getElementById('results').innerHTML = "<div style='font-size: 20px; text-align: center; margin-top: 10px'><p>Oups, ce que vous cherchez n'existe pas encore !</p></div>";
                    }
                }
            })
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM