问题描述
我正在尝试创建一个搜索栏,以更新数据库中找到的项目列表,例如该搜索栏的值。这是我的酒吧代码:
$(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>";
}
}
})
}
}