jq.ajax+php+mysql實現(xiàn)關(guān)鍵字模糊查詢(示例講解)
對于這個功能企業(yè)上還算比較實用,推薦給大家;
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<style>
*{margin:0;padding:0;}
.text{width:200px;height:30px;line-height:30px;font-size:14px;outline:none;}
ul{width:200px;height:auto;border:1px solid #999;border-top:none;}
ul li{width:200px;height:30px;line-height:30px;font-size:14px;}
li:hover{background:#ddd;}
</style>
<body>
<input type="text" class="text" name="text">
<ul class="sea"></ul>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(".text").bind("input", function() {
if($(this).val().length>0){
search();
}else{
$(".sea").html('');
}
})
function search(){
$.ajax({
type:"GET",
url:"sea.php",
data:{"text":$(".text").val()},
success:function(response){
//轉(zhuǎn)換成json對象
eval("var json="+response);
//console.log(json)
var str="";
for(var i=0;i<json.length;i++){
str += "<li>" + json[i].sea + "</li>";
}
$(".sea").html(str);
}
})
}
</script>
</body>
</html>
sea.php
<?php
$con = mysqli_connect("localhost","username","password");
if(!$con){
echo "數(shù)據(jù)庫鏈接失敗";
exit;
}
mysqli_select_db($con,'jwhuang');
mysqli_query($con,'set names utf-8');
$text= isset($_GET['text']) ? trim($_GET['text']) : '';
$result=mysqli_query($con,"select * from search where sea LIKE '{$text}%' ");
$search=array();
while($row=mysqli_fetch_assoc($result)){
//判斷是否有對應(yīng)的數(shù)據(jù)
if(!$row){
$search='';
exit;
}else{
//對查詢關(guān)鍵字進行標(biāo)記
$row['sea'] = str_replace($text, '<font color="red">' .$text. '</font>', $row['sea']);
$search[]=$row;
}
}
echo json_encode($search);
?>
效果圖

完整代碼下載:https://github.com/jwhuang59/Demos/tree/master/search
以上這篇jq.ajax+php+mysql實現(xiàn)關(guān)鍵字模糊查詢(示例講解)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaScript 網(wǎng)頁中實現(xiàn)一個計算當(dāng)年還剩多少時間的倒數(shù)計時程序
這篇文章主要介紹了JavaScript 網(wǎng)頁中實現(xiàn)一個計算當(dāng)年還剩多少時間的倒數(shù)計時程序,需要的朋友可以參考下2017-01-01
javascript實現(xiàn)文本框標(biāo)簽驗證的實例代碼
這篇文章主要介紹了javascript實現(xiàn)文本框標(biāo)簽驗證的實例代碼,需要的朋友可以參考下2018-10-10
javascript設(shè)計模式之module(模塊)模式
這篇文章主要為大家詳細介紹了javascript設(shè)計模式之module(模塊)模式 ,感興趣的小伙伴們可以參考一下2016-08-08
Javascript call及apply應(yīng)用場景及實例
這篇文章主要介紹了Javascript call及apply應(yīng)用場景及實例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
JavaScript幾種常見循環(huán)遍歷使用和區(qū)別
這篇文章主要介紹了JavaScript幾種常見循環(huán)遍歷使用和區(qū)別,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09

