PHP实现类似百度搜索自动完成(代码简单)
生活随笔
收集整理的這篇文章主要介紹了
PHP实现类似百度搜索自动完成(代码简单)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、效果圖:
?
?
二、HTML代碼
<html lang="en"> <head><meta charset="utf-8"><title>jQuery UI 自動(dòng)完成(Autocomplete) - 默認(rèn)功能</title><link rel="stylesheet" href="/public/AutoCom/jquery-ui.css"><script src="/public/AutoCom/jquery-1.91.js"></script><script src="/public/AutoCom/jquery-ui.js"></script><script>$(function() {$( "#tags" ).autocomplete({// source: availableTagssource: "at.php"});});</script> </head> <body><div class="ui-widget"><label for="tags">標(biāo)簽:</label><input id="tags" name="tags" > </div></body> </html>?
?
三、PHP代碼
<?php function test($keyword) {//連接數(shù)據(jù)庫(kù)$dsn = "mysql:dbname=test;host=localhost;";$db = new PDO($dsn, 'root', 'root');//查詢(xún)數(shù)據(jù)$result = $db->prepare("select title from article where title like :title");$result->execute(array('title' => "%" . $keyword . "%"));$data = $result->fetchall(PDO::FETCH_ASSOC);//將二維數(shù)組轉(zhuǎn)化為一維數(shù)組(自動(dòng)補(bǔ)全插件要求的是一個(gè)一維數(shù)組)foreach ($data as $k => $v) {$datas[] = $v['title'];}return $datas; }//獲取輸入框的內(nèi)容 //注:jquery-ui的自動(dòng)補(bǔ)全ajax 當(dāng)我們輸入一個(gè)c時(shí),Autocomplete實(shí)際發(fā)送的請(qǐng)求路徑為at.php?term=c $keyword = $_GET['term'];//根據(jù)用戶(hù)輸入值查詢(xún)相關(guān)數(shù)據(jù) $data = test($keyword); //輸出json字符串 echo json_encode($data); //輸出查詢(xún)的結(jié)果(json格式輸出)?>?
備注:HTML部分引入的css,js源代碼:
<!-- 引入jQuery UI的css文件 --> <link href="http://code.jquery.com/ui/1.10.4/themes/ui-darkness/jquery-ui.css" /> <!-- 引入jQuery的js文件 --> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js" ></script> <!-- 引入jQuery UI的js文件 --> <script type="text/javascript" src="http://code.jquery.com/ui/1.10.4/jquery-ui.js" ></script>文章參考:http://www.365mini.com/page/jquery-ui-autocomplete.htm
更多功能可參考:?http://www.runoob.com/jqueryui/example-autocomplete.html
如果js和css源代碼地址找不到,到這里下載
?
總結(jié):以上是結(jié)合mysql 和 jquery-ui實(shí)現(xiàn)的自動(dòng)提示,實(shí)際上如果數(shù)據(jù)庫(kù)數(shù)據(jù)量較大的情況,整體對(duì)數(shù)據(jù)庫(kù)開(kāi)銷(xiāo)也比較大。
這樣,也可以嘗試使用全文檢索工具 xunsearch 或 sphinx 來(lái)實(shí)現(xiàn)。好處是減少了mysql數(shù)據(jù)庫(kù)的查詢(xún)壓力,提高了檢索速度。
xunSearch的使用:https://blog.csdn.net/m_nanle_xiaobudiu/article/details/81663636
總結(jié)
以上是生活随笔為你收集整理的PHP实现类似百度搜索自动完成(代码简单)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: php类精确验证身份证号码
- 下一篇: php面试题2018