gpt4 book ai didi

javascript - AJAX - 尝试使用 debounce 实现实时搜索

转载 作者:搜寻专家 更新时间:2023-10-31 21:23:35 24 4
gpt4 key购买 nike

我尝试用 AJAX 实现 AJAX 实时搜索,我做得很好。然后我尝试添加 _.debounce 函数,这样它就不会使服务器过载,但效果不佳..

这是代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", _.debounce(function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
}),250);

// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</body>
</html>

这是 php 文件:

<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");

// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);

if(isset($query)){
// Attempt select query execution
$sql = "SELECT * FROM countries WHERE name LIKE '" . $query . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found for <b>$query</b></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}

// close connection
mysqli_close($link);
?>

谢谢!

最佳答案

您的代码不包含 Underscore 库,因此 _.debounce() 将无法使用。也就是说,您可以通过使用 setTimeout() 调用非常轻松地实现该方法的功能:

var timeout;
$('.search-box input[type="text"]').on("keyup input", function() {
var term = $(this).val();
var $resultDropdown = $(this).siblings(".result");

clearTimeout(timeout);
timeout = setTimeout(function() {
if (term.trim().length) {
$.get("backend-search.php", { query: term }).done(function(data) {
$resultDropdown.html(data);
});
} else {
$resultDropdown.empty();
}
}, 250);
});

关于javascript - AJAX - 尝试使用 debounce 实现实时搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41220243/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com