原生Ajax实现搜索联想和自动补全

使用原生的Ajax和js实现搜索联想和自动补全

效果如下:

搜索联想和自动补全

前台代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax实现搜索联想和自动补全</title>
    <style>
        .datagrid {
            width: 500px;
            height: 500px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%,-50%);
        }
        .userInput {
            width: 300px;
            height: 25px;
            font-size: 20px;
            padding-left: 5px;
            background-color: orange;
        }
        .showDiv {
            width: 309px;
            border: 1px solid black;
            background-color: darkkhaki;
            display: none;
        }
        .showDiv p {
            padding-left: 5px;
            margin-top: 3px;
            margin-bottom: 3px;
        }
        .showDiv p:hover{
            cursor: pointer;
            border: 1px blueviolet solid;
            background-color: chocolate;
        }

    </style>
</head>
<body>

<script type="text/javascript">
    window.onload = () =>{
        document.getElementById("keywords").onkeyup = function(){
            if(this.value == ""){
                document.getElementById("dataDiv").style.display = "none"
            }else{
                //发送ajax请求
                const xmlHttpRequest = new XMLHttpRequest()
                xmlHttpRequest.onreadystatechange = () =>{
                    if (xmlHttpRequest.readyState == 4) {
                        if (xmlHttpRequest.status >= 200 && xmlHttpRequest.status < 300) {
                            //[{"content":"javaee"},{},{}]
                            const json = JSON.parse(xmlHttpRequest.responseText)
                            //遍历数组
                            let html = ""
                            for (let i = 0; i < json.length; i++){
                                html +="<p onclick= 'myClick(\""+json[i].content+"\")'>"+json[i].content + "</p>"
                            }
                            document.getElementById("dataDiv").innerHTML = html
                            document.getElementById("dataDiv").style.display = "block"
                        }
                    }
                }
                xmlHttpRequest.open("GET","/AJAX/autocomplete_query?_="+new Date().getTime()+"&keywords=" + this.value,true)
                xmlHttpRequest.send()
            }
        }
    }
    function myClick(e){
        document.getElementById("keywords").value = e;
        document.getElementById("dataDiv").style.display = "none"
    }
</script>

<div class="datagrid">
    <div>
        <input type="text" class="userInput" id="keywords">
    </div>
    <div id="dataDiv" class="showDiv">
    </div>
</div>


</body>
</html>

后台代码:

package com.llw.study.ajax;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jdbcutil.DBUtil;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author :By-llw
 * @date :Created 2022/10/26 22:37
 * @description:Ajax实现自动联想补全
 */

@WebServlet("/autocomplete_query")
public class AutoCompleteAction extends jakarta.servlet.http.HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String keywords = request.getParameter("keywords");

        //拼接JSON用
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        //JDBC
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        boolean flag = false;
        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();
            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.toString().substring(0 , sb.length() - 1) + "]");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值