• Ajax——Ajax实现自动补全


    说明:
        本篇文章主要总结的是:利用Ajax实现搜索框的自动补全功能,即:用户输入数据之后,服务器前往数据库中查询用户输入的类似的数据,并且展示在搜索框下方,当用户点击查询列表时可以将对应的内容设置到搜索框中。

    1. 搜索联想,自动补全概述

    • 百度是一个很典型的代表。在百度的搜索框中输入相关信息的时候,会有搜索联想以及自动补全。
    • 搜索联想和自动补全:实际上是为了方便用户的使用。让用户的体验更好。
    • 搜索联想:当用户输入一些单词之后,自动联想出用户要搜索的信息,给一个提示。
    • 自动补全:当联想出一些内容之后,用户点击某个联想的单词,然后将这个单词自动补全到搜索框当中。
    • 搜索联想和自动补全功能,因为是页面局部刷新效果,所以需要使用ajax请求来完成。

    2. 自动补全功能实现原理

    • 当键盘事件发生之后,比如:keyup:键弹起事件。
    • 发送ajax请求,请求中提交用户输入的搜索内容,例如:北京(发送ajax请求,携带“北京”两个字)
    • 后端接收到ajax请求,接收到“北京”两个字,执行select语句进行模糊查询。返回查询结果。
    • 将查询结果封装成json格式的字符串,将json格式的字符串响应到前端。
    • 前端接收到json格式的字符串之后,解析这个json字符串,动态展示页面。

    3. 自动补全功能代码实现

    • 前端代码:包括了文本框,显示联想内容的div,数据样式,发送Ajax请求,处理响应的数据…
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>ajax实现搜索和自动补全title>
        <style type="text/css">
            .userInput{
                width: 300px;
                height: 25px;
                font-size: 15px;/*字体大小设置*/
                padding-left: 6px;/*内补丁*/
            }
            .showData{
                width: 309px;
                border: 1px solid black;
                background: sandybrown;
                display: none;
            }
    
            .showData p{
                padding-left: 5px;
                margin-top: 2px;
                margin-bottom: 3px;
            }
    
            .showData p:hover{
                cursor: pointer;
                border: 1px blue solid ;
                background-color: burlywood;
            }
        style>
    head>
    <body>
    <script type="text/javascript">
        window.onload = function (){
            document.getElementById("keywords").onkeyup = function () {//绑定文本框键盘弹起事件
    
                if (this.value == ""){
                    document.getElementById("showData").style.display = "none"
                }else {
                    //this表示的是文本框,因此this.value表示的就是文本框中的数据
                    //1.创建XMLHttpRequest核心对象
                    var xmlHttpRequest = new XMLHttpRequest();
                    //2.注册回调函数
                    xmlHttpRequest.onreadystatechange = function () {
                        if (xmlHttpRequest.readyState == 4) {
                            if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
                                const json = JSON.parse(xmlHttpRequest.responseText);
                                let html = ""
                                for (var i = 0; i < json.length; i++) {
                                    html += "

    "+json[i].content+"

    "
    } document.getElementById("showData").innerHTML = html document.getElementById("showData").style.display = "block" } } } //3.打开通道 xmlHttpRequest.open("GET","/ajax_autocomplete/query?t="+new Date().getTime()+"&keywords="+this.value,true) //4.发送数据 xmlHttpRequest.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"> <p>郑州天气p> <P>郑州720特大暴雨P> <p>郑州地铁p> <p>郑州人p> div> body> html>
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 后端代码:包括连接数据库,数据查询,结果集处理,响应数据到前端…
    package com.lcl.ajax.servlet;
    
    import com.lcl.ajax.util.DBUtil;
    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.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    /**
     * @Author Administration
     * @PackageName NewWeb
     * @Package com.lcl.ajax.servlet
     * @Date 2022/8/21 15:50
     * @Description:
     */
    @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();
    
            try {
                conn = DBUtil.getConnection();
                String sql = "select content from t_ajax where content like ?";
                ps = conn.prepareStatement(sql);
                ps.setString(1, keywords + "%");
                rs = ps.executeQuery();
                //[{"content":"javaweb"},{"content":"java"}]
                sb.append("[");
                while (rs.next()) {
                    String content = rs.getString("content");
                    sb.append("{\"content\":\"" + content + "\"},");
                }
    
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DBUtil.close(conn, ps, rs);
            }
            response.setContentType("text/html;charset=UTF-8");
            response.getWriter().print(sb.substring(0, sb.length() - 1) + "]");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    1. 实现效果展示

    <1>输入数据后,自动联想
    在这里插入图片描述
    <2>用户点击时可以更新用户选择的数据
    在这里插入图片描述

    <3>点击内容自动填补文本框

    在这里插入图片描述

  • 相关阅读:
    Vue3+node.js网易云音乐实战项目(七)
    KITTI raw_data数据集百度云下载
    链表的常见数据结构及题目
    Android及iOS黑客教程
    Docker安装并使用Mysql(可用详细)
    自然语言处理 Paddle NLP - 预训练语言模型及应用
    Golang分布式应用之ZooKeeper
    【无标题】
    win10中ros与ubuntu中ros通信
    Spring Boot
  • 原文地址:https://blog.csdn.net/weixin_44606952/article/details/126452206