搜索联想应用很是普遍,百度,谷歌,搜狗,淘宝,天猫,京东,以及不少网站都有,只须要打上几个字,就有相关的搜索提示。javascript
经过javascript监听搜索框的内容,调用后端便可。
(1)javascript监听搜索框的内容
(2)把搜索框的关键词传给后端进行搜索
(3)搜索到结果,遍历到页面php
index.htmlcss
<!DOCTYPE html> <html> <head> <title>test</title> <meta charset="utf-8"> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style type="text/css"> #input-content{ width: 350px; height: 200px; margin:100px auto 20px; } #input-content input{ width: 100%; height: 50px; text-indent: 15px; font-size: 18px; outline: none; border:2px solid #333; border-radius: 100px; } /*输入框底部黄色背景去除*/ input:-webkit-autofill, textarea:-webkit-autofill, select:-webkit-autofill { -webkit-box-shadow: 0 0 0 1000px white inset; } input[type=text]:focus, input[type=password]:focus, textarea:focus { -webkit-box-shadow: 0 0 0 1000px white inset; } </style> </head> <body> <!-- 表单 --> <form> <div id="input-content"> <h1>Ajax无刷新搜索</h1> <input id="inputView" type="text" name="keyword" placeholder="请输入关键词"> <div> </form> <!-- 搜索结果 --> <div id="result"></div> <!-- 监听输入框 --> <script type="text/javascript"> $("#inputView").bind("input propertychang",function(event){ var keyword = $.trim(this.value); // ajax搜索 $.ajax({ type: "GET", url: "server.php?keyword="+keyword, success:function(data){ if (keyword == '') { $("#result").html("<p>关键词不得为空</p>"); } else if (data[0].code == 202) { $("#result").html("<p>暂无搜索结果</p>"); } else { // 用empty()清空append() $("#result").empty(); // 再循环遍历列表 for (var a in data){ var resname = data[a].resname; $("#result").append("<p>"+resname+"</p>"); } } }, error : function() { console.log("服务器错误") } }); }); </script> </body> </html>
server.phphtml
<?php header("Content-type:application/json"); // 建立链接 $conn = new mysqli("数据库服务器", "数据库帐号", "数据库密码","数据库名"); // 得到关键词 $keyword = trim($_GET["keyword"]); // 过滤关键词 if(empty($keyword)){ $results_search = array( "code" => "201", "msg" => "关键词不得为空" ); }else{ mysqli_query($conn, "SET NAMES UTF-8"); //utf8 设为对应的编码 $sql_search = "SELECT * FROM 表名 WHERE 须要搜索的字段 LIKE '%$keyword%' ORDER BY ID DESC"; $result_search = $conn->query($sql_search); if ($result_search->num_rows > 0) { // 结果集是一个数组 $results_search = array(); while($row_search = $result_search->fetch_assoc()) { // 把搜索结果集存进一个数组 $results_search[] = $row_search; } } else { // 搜索无果 $results_search[] = array( "code" => "202", "msg" => "暂无搜索结果" ); } // 断开数据库链接 $conn->close(); } // 返回结果 echo json_encode($results_search,JSON_UNESCAPED_UNICODE); ?>
http://www.likeyunba.com/demo...java
Author:TANKING
Date:2020-11-14
Web:http://www.likeyun.cn/
WeChat:face6009mysql