我试图找出为什么我可以让我的实时搜索工作但它返回mysql表的所有结果,无论我输入什么。也许你可以帮忙吗?
我正在尝试获取上一个请求并在每个密钥上启动一个新请求。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Help Tool 2.0</title>
<link type="text/css" rel="stylesheet" href="assets/css/index.css" />
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
$('#search-box').keyup(function() {
$("#results").html('');
var xhr;
var keywords = $(this).val();
if(xhr != null) xhr.abort();
xhr = $.get("search.php", {q: keywords}, function() {
//alert("success");
})
.success(function(data) {
xhr = null;
//alert("second success");
$("#results").html(data);
})
});
});
</script>
<input id="search-box" name="q" type="text" />
<div id="results"></div>
</body>
</html>
PHP:
<?php
include_once ('database_connection.php');
if(isset($_GET['q'])){
$keyword = trim($_GET['q']) ;
$keyword = mysqli_real_escape_string($dbc, $keyword);
$query = "select topictitle,topicdescription from topics where topictitle like '%$q%' or topicdescription like '%$q%'";
//echo $query;
$result = mysqli_query($dbc,$query);
if($result){
if(mysqli_affected_rows($dbc)!=0){
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
echo '<p> <b>'.$row['topictitle'].'</b> '.$row['topicdescription'].'</p>';
}
}else {
echo 'No Results for :"'.$_GET['q'].'"';
}
}
}else {
echo 'Parameter Missing';
}
?>
答案 0 :(得分:12)
尝试使用此js代码代替您所拥有的代码。我添加了延迟功能,以便脚本在用户停止键入之后等待指定的时间,然后再发送请求。这可以防止大量请求被发送到服务器。
<script type="text/javascript">
var delay = (function() {
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$("#search-box").keyup(
function () {
delay(function () {
var keyword = $("#search-box").val();
var URL = encodeURI("search.php?q=" + keyword);
$.ajax({
url: URL,
cache: false,
type: "GET",
success: function(response) {
$("#results").html(response);
}
});
}, 500);
}
);
</script>