目录
什么是搜索联想?自动补全?
-
百度是一个很典型的代表。在百度的搜索框中输入相关信息的时候,会有搜索联想以及自动补全。
-
搜索联想和自动补全:实际上是为了方便用户的使用。让用户的体验更好。
-
搜索联想:当用户输入一些单词之后,自动联想出用户要搜索的信息,给一个提示。
-
自动补全:当联想出一些内容之后,用户点击某个联想的单词,然后将这个单词自动补全到搜索框当中。
-
搜索联想和自动补全功能,因为是页面局部刷新效果,所以需要使用ajax请求来完成。
-
搜索联想,自动补全功能的核心实现原理?
-
当键盘事件发生之后,比如:keyup:键弹起事件。
-
发送ajax请求,请求中提交用户输入的搜索内容,例如:北京(发送ajax请求,携带“北京”两个字)
-
后端接收到ajax请求,接收到“北京”两个字,执行select语句进行模糊查询。返回查询结果。
-
将查询结果封装成json格式的字符串,将json格式的字符串响应到前端。
-
前端接收到json格式的字符串之后,解析这个json字符串,动态展示页面。
最终程序完成效果:
实现:
1.创建autocomplete.html文件,发送Ajax请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax实现搜索和自动补全功能</title>
<style>
.userInput{
width: 300px;
height: 25px;
font-size: 20px;
padding-left: 5px;
}
.showDataDiv{
width: 310px;
border: 1px solid lightgray;
background-color: antiquewhite;
display: none;
}
.showDataDiv p{
padding-left: 5px;
margin-top: 2px;
margin-bottom: 2px;
}
.showDataDiv p:hover{
cursor: pointer;
border: 1px solid blue;
background-color: aliceblue;
}
</style>
</head>
<body>
<script type="text/javascript">
window.onload=()=>{
document.getElementById("keywords").onkeyup=function () {
if (this.value == "") {
document.getElementById("data").style.display="none"
}else {
document.getElementById("data").style.display="block"
}
//发送ajax请求
//1.发送ajax核心对象
const xmlHttpRequest = new XMLHttpRequest();
//2.注册回调函数
xmlHttpRequest.onreadystatechange=()=>{
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
const json = JSON.parse(xmlHttpRequest.responseText);
//遍历数组
let html =""
for (let i =0; i < json.length; i++) {
html += "<p onclick='setInput(\""+json[i].content+"\")'>"+json[i].content+"</p>"
}
document.getElementById("data").innerHTML = html
//显示出来
document.getElementById("data").style.display="block"
}
}
}
//3.开启通道
xmlHttpRequest.open("GET","/query?_="+new Date().getTime()+"&keywords="+this.value,true)
//4.发送请求
xmlHttpRequest.send()
}
}
function setInput(content) {
document.getElementById("keywords").value=content
document.getElementById("data").style.display="none"
}
</script>
<input type="text" class="userInput" id="keywords">
<div id="data" class="showDataDiv">
</div>
</body>
</html>
2.创建一张数据库表,为实现搜索联想做准备
3..创建servlet类,使用JDBC连接MySQL数据库,接收Ajax请求,返回后台数据。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
@WebServlet("/query")
public class QueryServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取用户输入的关键字
String keywords = request.getParameter("keywords");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
StringBuilder sb = new StringBuilder();
sb.append("[");
try {
//1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8", "root", "123456");
//3.写sql语句
String sql="select content from t_ajax where content like ?";
ps= conn.prepareStatement(sql);
ps.setString(1,keywords+"%");
//遍历结果集
rs= ps.executeQuery();
while (rs.next()){
String content = rs.getString("content");
sb.append("{\"content\":\""+content+"\"},");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//6.释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(sb.subSequence(0,sb.length()-1)+"]");
}}
4.启动Tomcat服务器打开浏览器,查看效果:
输入字母实现模糊查询
点击关键字会把关键字自动输入到文本框
如果文本框内容为空,则把内容隐藏起来