• 案例:AJAX实现搜索联想 自动补全


    什么是搜索联想?自动补全

    • 百度是一个很典型的代表。在百度的搜索框中输入相关信息的时候,会有搜索联想以及自动补全。
    • 搜索联想和自动补全:实际上是为了方便用户的使用。让用户的体验更好。
    • 搜索联想:当用户输入一些单词之后,自动联想出用户要搜索的信息,给一个提示。
    • 自动补全:当联想出一些内容之后,用户点击某个联想的单词,然后将这个单词自动补全到搜索框当中。
    • 搜索联想和自动补全功能,因为是页面局部刷新效果,所以需要使用ajax请求来完成。
    • 搜索联想,自动补全功能的核心实现原理?
      • 当键盘事件发生之后,比如:keyup:键弹起事件。
      • 发送ajax请求,请求中提交用户输入的搜索内容,例如:北京(发送ajax请求,携带“北京”两个字)
      • 后端接收到ajax请求,接收到“北京”两个字,执行select语句进行模糊查询。返回查询结果。
      • 将查询结果封装成json格式的字符串,将json格式的字符串响应到前端。
      • 前端接收到json格式的字符串之后,解析这个json字符串,动态展示页面。

    实现:

    前端代码:

    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>
    • 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

    后端代码:

    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();
                    }
                }
            }
        }
    }
    
    
    • 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

    在这里插入图片描述
    在这里插入图片描述

  • 相关阅读:
    30、Java高级特性——Java API、枚举、包装类、装箱和拆箱
    Redis 缓存过期淘汰策略
    Spring读书笔记——bean创建(上)
    1032 Sharing
    (十八)devops持续集成开发——使用docker安装部署jenkins流水线服务
    [HDLBits] Dualedge
    2022强网杯-07-30-re-GameMaster
    Anaconda使用笔记
    Spring项目配置
    virtio frontend and backend
  • 原文地址:https://blog.csdn.net/m0_53881899/article/details/126743470