亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

jQuery 搜索欄實時更新

jQuery 搜索欄實時更新

HUH函數 2023-02-24 17:07:54
我正在嘗試制作一個搜索欄來更新在數據庫中找到的項目列表,這些項目喜歡這個搜索欄的值。這是我的酒吧代碼:$(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(換句話說,動態)。有人對我的問題有任何提示嗎?提前謝謝了 !
查看完整描述

1 回答

?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

在 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>";

                    }

                }

            })

        }

}


查看完整回答
反對 回復 2023-02-24
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號