AJAX实现模糊查询和自动补全
前端代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>AJAX实现 内容搜索 自动补全</title>
</head>
<style>
.big {
width: 310px;
height: auto;
background-color: aqua;
position: relative;
left: 550px;
margin-top: 100px;
}
.findBox {
width: 300px;
height: 15px;
padding-left: 5px;
background-color: burlywood;
font-size: 7px;
}
.result {
width: 300px;
padding-left: 5px;
background-color: brown;
display: none;
}
.result p {
padding-left: 5px;
margin-top: 3px;
margin-bottom: 3px;
margin-left: 5px;
}
.result p:hover {
background-color: chartreuse;
}
</style>
<script type="text/javascript">
function clickResult(data){
document.getElementById("find").value=data;
document.getElementById("getBox").style.display="none";
}
window.onload = function (){
document.getElementById("find").onkeyup = function (){
var key = document.getElementById("find").value;
if(key==""){
document.getElementById("getBox").style.display="none";
}else{
var xhr = new XMLHttpRequest();
var html="";
xhr.onreadystatechange = function (){
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
//[{"content":"java"},{"content":"javascript"},{"content":"javaSE"}]
let data = JSON.parse(xhr.responseText);
for (let i = 0; i < data.length; i++) {
html +="<p οnclick='clickResult(\""+data[i].content+"\")'>"+data[i].content+"</p>"
}
document.getElementById("getBox").innerHTML = html;
document.getElementById("getBox").style.display ="block";
}
}
}
xhr.open("GET","/ajax/jquery?key="+key,true);
xhr.send();
}
}
}
</script>
<body>
<div class="big">
<input type="text" id="find" class="findBox"><br>
<div class="result" id="getBox">
</div>
</div>
</body>
</html>
后端代码:
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
@WebServlet(value = "/jquery")
public class SearchServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String key = request.getParameter("key");
String[] arrays = {"javaScript","java","javaSE","javaWeb","linux","springMVC","MyBatis"};
List<String> result = null;
StringBuilder json = new StringBuilder();
json.append("[");
for (int i = 0; i < arrays.length; i++) {
if(arrays[i].startsWith(key)){
json.append("{\"content\":\""+arrays[i]+"\"},");
}
}
String s = json.subSequence(0, json.length() - 1) + "]";
response.getWriter().print(s);
}
}
整体逻辑:
前端写好页面,将查询结果的div隐藏起来,等键盘事件触发,查处结果就将该div显示出来,反之不显示。事件触发的逻辑:获取文本框输入的值,将值获取,发送至后端,后端经过模糊查询获取数据,以json数组的形式将值传至前端,前端解析json数组后,将值填充进p标签中,最后将p标签的组成HTML代码放至结果div中;