當前位置:
首頁 >
PHP实现类似百度搜索自动完成(代码简单)
發布時間:2023/12/4
38
豆豆
生活随笔
收集整理的這篇文章主要介紹了
PHP实现类似百度搜索自动完成(代码简单)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、效果圖:
?
?
二、HTML代碼
<html lang="en"> <head><meta charset="utf-8"><title>jQuery UI 自動完成(Autocomplete) - 默認功能</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">標簽:</label><input id="tags" name="tags" > </div></body> </html>?
?
三、PHP代碼
<?php function test($keyword) {//連接數據庫$dsn = "mysql:dbname=test;host=localhost;";$db = new PDO($dsn, 'root', 'root');//查詢數據$result = $db->prepare("select title from article where title like :title");$result->execute(array('title' => "%" . $keyword . "%"));$data = $result->fetchall(PDO::FETCH_ASSOC);//將二維數組轉化為一維數組(自動補全插件要求的是一個一維數組)foreach ($data as $k => $v) {$datas[] = $v['title'];}return $datas; }//獲取輸入框的內容 //注:jquery-ui的自動補全ajax 當我們輸入一個c時,Autocomplete實際發送的請求路徑為at.php?term=c $keyword = $_GET['term'];//根據用戶輸入值查詢相關數據 $data = test($keyword); //輸出json字符串 echo json_encode($data); //輸出查詢的結果(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源代碼地址找不到,到這里下載
?
總結:以上是結合mysql 和 jquery-ui實現的自動提示,實際上如果數據庫數據量較大的情況,整體對數據庫開銷也比較大。
這樣,也可以嘗試使用全文檢索工具 xunsearch 或 sphinx 來實現。好處是減少了mysql數據庫的查詢壓力,提高了檢索速度。
xunSearch的使用:https://blog.csdn.net/m_nanle_xiaobudiu/article/details/81663636
總結
以上是生活随笔為你收集整理的PHP实现类似百度搜索自动完成(代码简单)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php类精确验证身份证号码
- 下一篇: php面试题2018