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>
相关推荐
千寻girling9 小时前
记录第一次学习 Docker
学习·docker·容器
Kobebryant-Manba10 小时前
学习RNN(简洁实现)
人工智能·rnn·学习
知南x10 小时前
【DPDK例程学习】(4) l2fwd
学习·word
努力努力再努力FFF10 小时前
大学四年AI能力规划:从入门学习到简历表达
人工智能·学习
Litluecat10 小时前
配合多角色提示语3,学习AI漫剧(刚开始学)
人工智能·学习·ai·提示词·短剧·漫剧
三品吉他手会点灯11 小时前
STM32F103 学习笔记-24-I2C-读写EEPROM(第1节)-I2C物理层介绍
笔记·stm32·学习
MartinYeung511 小时前
[论文学习]大型语言模型中个人可识别资讯(PII)的机器遗忘技术:UnlearnPII 基准与 PERMU_tok 方法的深度分析
人工智能·学习·语言模型
fanged11 小时前
Linux内核学习21--V4L2学习3(应用)(TODO)
学习
万物更新_12 小时前
vue框架
前端·javascript·vue.js·笔记
上海观智网络12 小时前
上海小程序定制开发合同怎么签?需要注意什么?
经验分享·笔记·小程序