jQuery 搜索栏实时更新

我正在尝试制作一个搜索栏来更新在数据库中找到的项目列表,这些项目喜欢这个搜索栏的值。这是我的酒吧代码:


$(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(换句话说,动态)。


有人对我的问题有任何提示吗?提前谢谢了 !


HUH函数
浏览 123回答 1
1回答

心有法竹

在 keyup 上发送 ajax 请求并不是很聪明。为什么?因为我可以向键盘发送 1000 次垃圾邮件,它会发送 1000 个请求。您可能想要做的是在用户完成输入后发送请求。var typingTimer;var doneTypingInterval = 1000; // Trigger the request 1 second/1000 ms after user done typing.var input = $('#input'); // Your inputinput.on('keyup', function () {&nbsp; clearTimeout(typingTimer);&nbsp; typingTimer = setTimeout(doneTyping, doneTypingInterval);});input.on('keydown', function () {&nbsp; clearTimeout(typingTimer);});// user is done, send ajax request.function doneTyping () {&nbsp; &nbsp;let searchValue = $('#input').val();&nbsp; &nbsp;if(searchValue !== ''){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; type: 'GET',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; url: '../controller/searchItem.php',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: 'data=' + encodeURIComponent(searchValue),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; success: function(data){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(data !== ""){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $('#results').append(data);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }else{&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 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>";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript