文章詳情頁
Ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動補(bǔ)全功能及遇到坑
瀏覽:154日期:2022-06-12 09:05:28
目錄
- 遇到的小坑
- 代碼實(shí)現(xiàn)
- 前端代碼
- 后端代碼
- 用到的實(shí)體類
- 自己封裝的jdbc工具類
- 數(shù)據(jù)庫表:
- 效果展示:
遇到的小坑
- 回調(diào)函數(shù)相對window.onload的擺放位置
- 給回調(diào)函數(shù)addData傳數(shù)據(jù)時,如何操作才能將數(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)想和自動補(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)用戶在文本框里輸入數(shù)據(jù)時,發(fā)生keyup事件時,將文本框里的數(shù)據(jù),以ajax請求方式提交的到后端 3. 后端對前端提交的關(guān)鍵字,在數(shù)據(jù)庫里進(jìn)行模糊查詢 4. 將后端查詢到的數(shù)據(jù)以json格式傳給前端 5. 前端解析后端傳來的數(shù)據(jù),將數(shù)據(jù)顯示在提示欄里 6. 當(dāng)用戶點(diǎn)擊提示中的某條提示信息時,將提示欄里的信息賦給輸入框,隱藏提示層 注意:1. 凡是輸入框里發(fā)生keyup事件時,都要進(jìn)行ajax請求提交,實(shí)時獲取提示信息 2. 輸入框信息為空時,也要隱藏提示層 --> <script>window.onload = function (){ //獲取dom對象 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時,發(fā)送ajax請求,傳遞文本框內(nèi)數(shù)據(jù) var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function (){if(this.readyState == 4){ if(this.status == 200){//解析后端傳來的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 = htmldiv_data.style.display = "block" }else{alert("異常狀態(tài)碼: " + this.status) }} } xmlHttpRequest.open("GET", "/ajax/ajaxAutoComplete?keyWords="+this.value+"", true) xmlHttpRequest.send()} }}function addData(perData){ //完成自動補(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 {//獲取前端傳來的關(guān)鍵字String keyWords = request.getParameter("keyWords");//連接數(shù)據(jù)庫,進(jìn)行模糊查詢Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;//封裝關(guān)鍵字對象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)鍵字對象KeyWords keyWordsObj = new KeyWords(content);//將關(guān)鍵字對象封裝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í)體類
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工具類
package com.examples.ajax.utils;import java.sql.*;import java.util.ResourceBundle;/** * 封裝自己的jdbc工具類 */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ù)庫表:
一張表: tb_search
數(shù)據(jù)表描述: 除了id, 就一個字段 content varchar(255) not null
效果展示:
自己在遠(yuǎn)程數(shù)據(jù)庫上用docker運(yùn)行了一個mysql數(shù)據(jù)庫,查詢速度比較慢,但演示關(guān)鍵字聯(lián)想和自動補(bǔ)全功能的測試目的已經(jīng)達(dá)到
到此這篇關(guān)于Ajax實(shí)現(xiàn)關(guān)鍵字聯(lián)想和自動補(bǔ)全功能的文章就介紹到這了,更多相關(guān)ajax關(guān)鍵字自動補(bǔ)全內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
標(biāo)簽:
Ajax
排行榜
