【发布时间】:2015-08-30 12:00:19
【问题描述】:
以下代码用于即时搜索,例如谷歌搜索。
请注意,我没有在此处包含连接到数据库功能。因为我认为数据库用户名和密码设置会与你的不同。所以如果你想测试它,请创建你自己的。 mysql设置了一个名为“objects”的表,它有一个名为“name”的列。
每当我输入任何内容时,都会弹出另一个新的搜索框,这是我期待的搜索结果。
有人可以帮忙吗?我坚持了将近一天,明天需要它工作..提前谢谢!
<!-- display the search area -->
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeydown="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
</html>
<?php
$output="";
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div>".$object_name."</div>";
}
}
}
?>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var searchTxt = $("input[name='search']").val();
// post the value
$.post("search.php",{searchVal: searchTxt},function(output){
$("#output").html(output);
});
}
</script>
【问题讨论】:
-
你不需要 jquery 来完成这样一个简单的任务。你可以在几分钟内用纯 javascript 完成它
标签: javascript php jquery html