php+mysql+jquery 簡易的檢索自動補全提示
阿新 • • 發佈:2018-11-10
這段時間看了一些關於自動補全提示方面的內容,發現大部分實現過程都十分複雜。心想這應該是一個比較簡單的功能啊,於是自己親自動手來小試一下。思路很常規,需要說明的是沒有為提示內容繫結鍵盤事件,僅可用滑鼠操作。
html+jquery內容
<html>
<head>
<style type="text/css">
#autoBox
{
margin: 0px;
padding: 0px;
border: 1px solid #CCCCCC;
width : 200px;
}
#autoBox li
{
clear: both;
background-color: white;
color: black;
position: relative;
top: 0px;
left: 0px;
line-height: 25px;
width:200px;
text-align: left;
overflow : hidden;
}
#autoBox li:hover
{
background-color: gray;
color: yellow;
cursor: pointer;
}
</style>
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function (){
$.ajaxSetup({cache:false}) ; //不快取
//以下程式碼用於顯示檢索提示框
$("#autoBox").hide(); //初始化時隱藏補全提示框
$("#stuSearch").keyup(function(){ //輸入框中的keyup事件啟用以下查詢行為
$("#autoBox").html(""); //先清空補全提示框原有內容
if($("#stuSearch").val().length>0) // 如果輸入框不為空
{
$.ajax({ //後臺呼叫php檔案進行查詢
type:"post",
url:"phpFiles/stuSearch.php",
dataType:"json",
data:{keywords:$("#stuSearch").val()},
success:function(feedbackdata)
{
$("#autoBox").show();// 顯示補全提示框
for(i=0;i<feedbackdata.length;i++) //將結果新增到提示框中
{
$("#autoBox").append("<li>"+feedbackdata[i]['truename']+"</li>");
}
$("#autoBox li").on("click",function(){ //為這些新增的li繫結單擊事件,單擊後將其值賦到輸入框中
$("#stuSearch").val($(this).text());
})
$("#autoBox").append("<li style='text-align:right'>關閉</li>");//在提示框的最後新增一個li用來關閉
$("#autoBox li:last").on("click",function(){ // 新增單擊事件,單擊後隱藏提示框
$("#autoBox").hide();
})
}
});
}
})
})
</script>
</head>
<body>
<input type="text" placeholder="輸入您想檢索的關鍵詞後回車。" id="stuSearch" name="stuSearch"/>
<ul id="autoBox">
</ul>
</body>
</html>
stuSearch.php程式碼
<?php
include '../phpFiles/connMysql.php';
$keywords=$_POST['keywords'];
$myrs=mysql_query("select * from users where truename like '".$keywords."%'");
if($myrs)
{
while($row=mysql_fetch_array($myrs))
{
$temp[]=$row;
}
echo(json_encode($temp));
}
?>
效果圖
輸入時:
點選某一項後: