AJAX学习笔记9 搜索联想自动补全

AJAX学习笔记8 跨域问题及解决方案_biubiubiu0706的博客-CSDN博客

其实就一个功能

搜索联想

自动补全

键盘按下事件keydown 键盘弹起事件keyup 做模糊查询

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax实现搜索联想自动补全</title>
    <style type="text/css">
        .userInput{
            width: 300px;
            height: 25px;
            font-size: 20px;
            margin-left: 20px;
            padding-left: 5px;
        }
        .showDataDiv{
            width: 300px;
            margin-left: 20px;
            border: 1px solid lightblue;
            background-color: antiquewhite;

        }
        .showDataDiv p{
            padding-left: 5px;
            margin-top: 3px;
            margin-bottom: 5px;
        }
        .showDataDiv p:hover{/*加小手*/
            cursor: pointer;
            border:1px blue solid;
            background-color: aliceblue;
        }
    </style>
</head>
<body>
<input type="text" class="userInput">
<div class="showDataDiv">
    <p>北京疫情最新情况</p>
    <p>北京天气</p>
    <p>北京时间</p>
    <p>北京房产</p>
    <p>北京美女</p>
</div>
</body>
</html>

加个display:none;就隐藏掉

插入数据库

引入fastjson,mysql 依赖

后端代码

复制代码
import com.alibaba.fastjson.JSON;

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.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hrui
 * @date 2023/9/7 9:53
 */
@WebServlet("/getAny")
public class GetAnyServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String keywords = req.getParameter("keywords");
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<Map> list=new ArrayList<>();

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("xxx", "xxx", "xxx");
            String sql="select id,content from t_ajax where content like ?";
            ps=conn.prepareStatement(sql);
            ps.setString(1, keywords+"%");
            rs = ps.executeQuery();

            while(rs.next()){
                String id = rs.getString("id");
                String content = rs.getString("content");
                Map<String,String> map=new HashMap<>();
                map.put("id", "id");
                map.put("content", content);
                list.add(map);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            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();
                }
            }
        }
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String s = JSON.toJSONString(list);
        writer.print(s);
    }
}

前端

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax实现搜索联想自动补全</title>
    <style type="text/css">
        .userInput{
            width: 300px;
            height: 25px;
            font-size: 20px;
            margin-left: 20px;
            padding-left: 5px;
        }
        .showDataDiv{
            width: 300px;
            margin-left: 20px;
            border: 1px solid lightblue;
            background-color: antiquewhite;
            display:none;
        }
        .showDataDiv p{
            padding-left: 5px;
            margin-top: 3px;
            margin-bottom: 5px;
        }
        .showDataDiv p:hover{/*加小手*/
            cursor: pointer;
            border:1px blue solid;
            background-color: aliceblue;
        }
    </style>
</head>
<body>
<script type="text/javascript">
    /*不使用JQuery*/
    window.onload=()=>{
        document.getElementById("keywords").onkeyup=()=>{
            let xhr=new XMLHttpRequest();
            xhr.onreadystatechange=()=>{
                if(xhr.readyState==4){
                    if(xhr.status>=200&&xhr.status<300){
                        //[{"id":"xxx","content":"xxxx"},{"id":"xxx","content":"xxxx"}]
                        const json=JSON.parse(xhr.responseText)
                        const html=""
                        for(let i=0;i<json.length;i++){
                            html+="<p onclick='setInput(\""+json[i].content+"\")'>"+json[i].content+"</p>"
                        }
                        document.getElementById("showDataDiv").innerHTML=html
                        //将div显示出来
                        document.getElementById("showDataDiv").style.display="block"
                    }
                }
            }
            console.log(this.value)
            xhr.open("get","/d/getAny?keywords="+this.value,true)
            xhr.send()
        }
    }

    function setInput(value){
        document.getElementById("keywords").value=value
        //将div隐藏
        document.getElementById("showDataDiv").style.display="none"
    }
</script>
<input type="text" class="userInput" id="keywords">
<div class="showDataDiv">
<!--    <p>北京疫情最新情况</p>-->
<!--    <p>北京天气</p>-->
<!--    <p>北京时间</p>-->
<!--    <p>北京房产</p>-->
<!--    <p>北京美女</p>-->
</div>
</body>
</html>
相关推荐
一隅论数智5 天前
给AI一张“业务概念地图“:本体如何从哲学走向企业智能
大数据·人工智能·经验分享·笔记·学习·学习方法·政务
XiHongShi20165 天前
STM32F407 RTC定时器例程,建议保存
stm32·单片机·学习
爱吃苹果的日记本5 天前
离散数学第六课
学习·离散数学
AI职业加油站5 天前
AI智能体应用工程师证书:政策红利下的职业新风口
大数据·运维·人工智能·学习·职场发展
深圳老胡5 天前
STM32F407 控制 L6470 步进电机驱动 —— 控制过程简介
笔记·stm32·单片机·嵌入式硬件·代码规范
旖旎夜光5 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
奇思妙想聪明勤奋的小羊5 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
Because_of_Her15 天前
并查集-听课笔记
笔记·算法·并查集
霍霍的袁5 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio