亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動(dòng)補(bǔ)全功能及遇到坑

 更新時(shí)間:2022年08月05日 09:17:15   作者:nefu-wangxun  
這篇文章主要介紹了Ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動(dòng)補(bǔ)全功能,實(shí)現(xiàn)代碼包括前端部分和后端部分,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

遇到的小坑

  • 回調(diào)函數(shù)相對(duì)window.onload的擺放位置
  • 給回調(diào)函數(shù)addData傳數(shù)據(jù)時(shí),如何操作才能將數(shù)據(jù)傳進(jìn)去

代碼實(shí)現(xiàn)

前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動(dòng)補(bǔ)全</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        #keyWords{
            margin-top: 10px;
            margin-left: 10px;
            width: 300px;
            height: 25px;
            font-size: 20px;
            padding-left: 5px;
        }
        #dataDiv{
            background-color: wheat;
            width: 300px;
            margin-left: 10px;
            display: none;
        }
        #dataDiv p{
            padding-left: 10px;
            padding-top: 7px;
            padding-bottom: 3px;
            cursor: pointer;
        }
        #dataDiv p:hover{
            background-color: cornflowerblue;
            color: white;
        }
    </style>
</head>
<body>
    <!--
        需求:
            1. 給定文本輸入框,顯示層,顯示層里的顯示欄
            2. 當(dāng)用戶(hù)在文本框里輸入數(shù)據(jù)時(shí),發(fā)生keyup事件時(shí),將文本框里的數(shù)據(jù),以ajax請(qǐng)求方式提交的到后端
            3. 后端對(duì)前端提交的關(guān)鍵字,在數(shù)據(jù)庫(kù)里進(jìn)行模糊查詢(xún)
            4. 將后端查詢(xún)到的數(shù)據(jù)以json格式傳給前端
            5. 前端解析后端傳來(lái)的數(shù)據(jù),將數(shù)據(jù)顯示在提示欄里
            6. 當(dāng)用戶(hù)點(diǎn)擊提示中的某條提示信息時(shí),將提示欄里的信息賦給輸入框,隱藏提示層
            注意:1. 凡是輸入框里發(fā)生keyup事件時(shí),都要進(jìn)行ajax請(qǐng)求提交,實(shí)時(shí)獲取提示信息
                 2. 輸入框信息為空時(shí),也要隱藏提示層
    -->
    <script>
        window.onload = function (){
            //獲取dom對(duì)象
            input_txt = document.getElementById("keyWords")
            div_data = document.getElementById("dataDiv")
            //為輸入框綁定keyup事件
            input_txt.onkeyup = function (){
                //輸入框?yàn)榭?,隱藏提示層
                if(this.value.trim() == ""){
                    div_data.style.display = "none"
                }else{
                    //每當(dāng)keyup時(shí),發(fā)送ajax請(qǐng)求,傳遞文本框內(nèi)數(shù)據(jù)
                    var xmlHttpRequest = new XMLHttpRequest();
                    xmlHttpRequest.onreadystatechange = function (){
                        if(this.readyState == 4){
                            if(this.status == 200){
                                //解析后端傳來(lái)的json數(shù)據(jù):[{"content" : "data"}, {}, {}]
                                var jsonArray = JSON.parse(this.responseText)
                                var html = ""
                                for(var i = 0; i < jsonArray.length; i++){
                                    var perData = jsonArray[i].content
                                    //為p標(biāo)簽綁定單擊事件,將數(shù)據(jù)以字符串的形式傳給回調(diào)函數(shù)
                                    html += "<p onclick='addData(\""+perData+"\")'>"+perData+"</p>"
                                }
                                div_data.innerHTML = html
                                div_data.style.display = "block"
                            }else{
                                alert("異常狀態(tài)碼: " + this.status)
                            }
                        }
                    }
                    xmlHttpRequest.open("GET", "/ajax/ajaxAutoComplete?keyWords="+this.value+"", true)
                    xmlHttpRequest.send()
                }
            }
        }
        function addData(perData){
            //完成自動(dòng)補(bǔ)全
            input_txt.value= perData
            //隱藏提示層
            div_data.style.display = "none"
        }
    </script>
    <input type="text" id="keyWords">
    <div id="dataDiv">
        <!--
        <p>java</p>
        <p>jsp</p>
        <p>service</p>
        <p>servlet</p>
        <p>docker</p>
        <p>linux</p>
        -->
    </div>
</body>
</html>

后端代碼

package com.examples.ajax.servlet;
import com.alibaba.fastjson.JSON;
import com.examples.ajax.beans.KeyWords;
import com.examples.ajax.utils.DBUtils;
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;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/ajaxAutoComplete")
public class AjaxRequest13 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //獲取前端傳來(lái)的關(guān)鍵字
        String keyWords = request.getParameter("keyWords");
        //連接數(shù)據(jù)庫(kù),進(jìn)行模糊查詢(xún)
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //封裝關(guān)鍵字對(duì)象
        List<KeyWords> keyWordsList = new ArrayList<>();
        try {
            conn = DBUtils.getConnection();
            String sql = "select content from tb_search where content like ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, keyWords + "%");
            rs = ps.executeQuery();
            while(rs.next()){
                String content = rs.getString("content");
                //封裝成關(guān)鍵字對(duì)象
                KeyWords keyWordsObj = new KeyWords(content);
                //將關(guān)鍵字對(duì)象封裝
                keyWordsList.add(keyWordsObj);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DBUtils.close(conn, ps, rs);
        }
        //后端數(shù)據(jù)json化
        String jsonKeyWordsArray = JSON.toJSONString(keyWordsList);
        //返回后端數(shù)據(jù)
        response.getWriter().write(jsonKeyWordsArray);
    }
}

用到的實(shí)體類(lèi)

package com.examples.ajax.beans;
public class KeyWords {
    private String content;
    public KeyWords() {
    }
    public KeyWords(String content) {
        this.content = content;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

自己封裝的jdbc工具類(lèi)

package com.examples.ajax.utils;
import java.sql.*;
import java.util.ResourceBundle;
/**
 * 封裝自己的jdbc工具類(lèi)
 */
public class DBUtils {
    static ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
    static String driver;
    static String url;
    static  String username;
    static  String password;
    static {
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    private DBUtils(){}
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}

數(shù)據(jù)庫(kù)表:

一張表: tb_search
數(shù)據(jù)表描述: 除了id, 就一個(gè)字段 content varchar(255) not null

效果展示:

自己在遠(yuǎn)程數(shù)據(jù)庫(kù)上用docker運(yùn)行了一個(gè)mysql數(shù)據(jù)庫(kù),查詢(xún)速度比較慢,但演示關(guān)鍵字聯(lián)想和自動(dòng)補(bǔ)全功能的測(cè)試目的已經(jīng)達(dá)到

到此這篇關(guān)于Ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動(dòng)補(bǔ)全功能的文章就介紹到這了,更多相關(guān)ajax關(guān)鍵字自動(dòng)補(bǔ)全內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論