Ajax實現關鍵字聯想和自動補全功能及遇到坑
遇到的小坑
- 回調函數相對window.onload的擺放位置
- 給回調函數adddata傳數據時,如何操作才能將數據傳進去
代碼實現
前端代碼
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>ajax實現關鍵字聯想和自動補全</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. 當用戶在文本框里輸入數據時,發生keyup事件時,將文本框里的數據,以ajax請求方式提交的到后端 3. 后端對前端提交的關鍵字,在數據庫里進行模糊查詢 4. 將后端查詢到的數據以json格式傳給前端 5. 前端解析后端傳來的數據,將數據顯示在提示欄里 6. 當用戶點擊提示中的某條提示信息時,將提示欄里的信息賦給輸入框,隱藏提示層 注意:1. 凡是輸入框里發生keyup事件時,都要進行ajax請求提交,實時獲取提示信息 2. 輸入框信息為空時,也要隱藏提示層 --> <script> window.onload = function (){ //獲取dom對象 input_txt = document.getelementbyid("keywords") div_data = document.getelementbyid("datadiv") //為輸入框綁定keyup事件 input_txt.onkeyup = function (){ //輸入框為空,隱藏提示層 if(this.value.trim() == ""){ div_data.style.display = "none" }else{ //每當keyup時,發送ajax請求,傳遞文本框內數據 var xmlhttprequest = new xmlhttprequest(); xmlhttprequest.onreadystatechange = function (){ if(this.readystate == 4){ if(this.status == 200){ //解析后端傳來的json數據:[{"content" : "data"}, {}, {}] var jsonarray = json.parse(this.responsetext) var html = "" for(var i = 0; i < jsonarray.length; i++){ var perdata = jsonarray[i].content //為p標簽綁定單擊事件,將數據以字符串的形式傳給回調函數 html += "<p onclick='adddata(\""+perdata+"\")'>"+perdata+"</p>" } div_data.innerhtml = html div_data.style.display = "block" }else{ alert("異常狀態碼: " + this.status) } } } xmlhttprequest.open("get", "/ajax/ajaxautocomplete?keywords="+this.value+"", true) xmlhttprequest.send() } } } function adddata(perdata){ //完成自動補全 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 { //獲取前端傳來的關鍵字 string keywords = request.getparameter("keywords"); //連接數據庫,進行模糊查詢 connection conn = null; preparedstatement ps = null; resultset rs = null; //封裝關鍵字對象 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"); //封裝成關鍵字對象 keywords keywordsobj = new keywords(content); //將關鍵字對象封裝 keywordslist.add(keywordsobj); } } catch (sqlexception e) { throw new runtimeexception(e); }finally { dbutils.close(conn, ps, rs); } //后端數據json化 string jsonkeywordsarray = json.tojsonstring(keywordslist); //返回后端數據 response.getwriter().write(jsonkeywordsarray); } }
用到的實體類
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); } } } }
數據庫表:
一張表: tb_search
數據表描述: 除了id, 就一個字段 content varchar(255) not null
效果展示:
自己在遠程數據庫上用docker運行了一個mysql數據庫,查詢速度比較慢,但演示關鍵字聯想和自動補全功能的測試目的已經達到
到此這篇關于ajax實現關鍵字聯想和自動補全功能的文章就介紹到這了,更多相關ajax關鍵字自動補全內容請搜索碩編程以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持碩編程!