我尝试用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);
?>
谢谢!
答案 0 :(得分:1)
您的代码不包含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);
});
答案 1 :(得分:1)
您可以通过设置 setTimeout 来实现此目的,以便在经过特定时间后对输入上发生的每个更改进行 ajax 调用,但不要忘记终止之前的调用。您可以使用下面的代码来声明任何功能。
var debounce;
$('#input').on('input', function (e) {
clearTimeout(debounce);
debounce = setTimeout(
function () {
searchText(e.target.value)
}, 1000
);
});