前端代码:
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;
}
.showData{
width: 310px;
border: 1px solid lightgray;
background-color: antiquewhite;
display: none;//隐藏标签
}
.showData p{
padding-left: 5px;
margin-top: 2px;
margin-bottom: 2px;
}
.showData p:hover{
cursor: pointer;
border: 1px blue solid;
background-color: aliceblue;
}
style>
head>
<body>
<script type="text/javascript">
window.onload = () =>{
document.getElementById("keywords").onkeyup = function() {//键盘弹起发送ajax请求异步刷新
if (this.value == "") {//内容为空不显示提示内容
document.getElementById("showData").style.display = "none";
}else{
//1.创建ajax和新对象
var xmlHttpRequet = new XMLHttpRequest();
//2.注册回调函数
xmlHttpRequet.onreadystatechange = () =>{
if(xmlHttpRequet.readyState == 4){
if (xmlHttpRequet.status == 200) {
var json = JSON.parse(xmlHttpRequet.responseText);
var html = "";
for (let i = 0; i < json.length; i++) {
html+="+json[i].content+"')\">"+json[i].content+"
";
}
document.getElementById("showData").innerHTML = html;
document.getElementById("showData").style.display = "block";
}
}
}
//3.开启通道
xmlHttpRequet.open("get","/xmm/showSearch?time="+new Date().getTime()+"&keywords="+this.value,true);//这里的this是input,因为箭头函数没有this
//4.发送请求
xmlHttpRequet.send();
}
}
}
function setInput(content){
document.getElementById("keywords").value = content;
document.getElementById("showData").style.display = "none";
}
script>
<input type="text" class="userInput" id="keywords" />
<div class="showData"id="showData">
div>
body>
html>
后端代码:
package aotoComplete;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ResourceBundle;
@WebServlet("/showSearch")
public class Autocomplete extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String keywords = request.getParameter("keywords");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
Connection con = null;
PreparedStatement pre = null;
ResultSet rs = null;
StringBuilder sb = new StringBuilder();
sb.append("[");
try {
Class.forName(rb.getString("driver"));
con = DriverManager.getConnection(rb.getString("url"),rb.getString("username"),rb.getString("password"));
pre = con.prepareStatement("select content from t_ajax where content like (?)");
pre.setString(1,keywords+"%");//模糊查询
rs = pre.executeQuery();
while(rs.next()){
String content = rs.getString("content");
sb.append("{\"content\":\""+content+"\"},");
}
out.print(sb.substring(0,sb.length()-1)+"]");
} catch (Exception e) {
e.printStackTrace();
}finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pre != null) {
try {
pre.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}

