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

- 回調(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)文章
ajax交互Struts2的action(客戶(hù)端/服務(wù)器端)
本文為大家探討下ajax交互Struts2的action并有客戶(hù)端及服務(wù)器端代碼,感興趣的朋友可以參考下,希望對(duì)大家有所幫助2013-08-08
ajax接口文檔url路徑的簡(jiǎn)寫(xiě)實(shí)例
前端工程師將來(lái)打交道最多的是Http API接口,此種接口會(huì)提供一個(gè)URL地址暴露在互聯(lián)網(wǎng)上,可以通過(guò)編寫(xiě)Ajax代碼去與之交互來(lái)完成功能,下面這篇文章主要給大家介紹了關(guān)于ajax接口文檔url路徑簡(jiǎn)寫(xiě)的相關(guān)資料,需要的朋友可以參考下2021-10-10
國(guó)內(nèi)首發(fā) -- ajax完整功能框架
國(guó)內(nèi)首發(fā) -- ajax完整功能框架2007-01-01
Ajax實(shí)現(xiàn)彈出式無(wú)刷新城市選擇功能代碼
這篇文章主要介紹了Ajax實(shí)現(xiàn)彈出式無(wú)刷新城市選擇功能代碼,實(shí)例分析了Ajax彈出窗口及無(wú)刷新選擇數(shù)據(jù)項(xiàng)的相關(guān)技巧,需要的朋友可以參考下2015-08-08
ajax回調(diào)函數(shù)中使用$(this)取不到對(duì)象的解決方法
如果在ajax的回調(diào)函數(shù)內(nèi)使用$(this)的話(huà),實(shí)踐證明,是取不到任何對(duì)象的,需要的朋友可以參考下2014-06-06
滑輪滾動(dòng)到頁(yè)面底部ajax加載數(shù)據(jù)配合jsonp實(shí)現(xiàn)探討
滾動(dòng)下拉到頁(yè)面底部加載數(shù)據(jù)是很多瀑布流網(wǎng)站的做法,那來(lái)看看配合jsonp是如何實(shí)現(xiàn)的吧,小菜總結(jié)記錄之用特在此與大家一起分享,感興趣的朋友可以參考下哈2013-05-05
ajax實(shí)現(xiàn)簡(jiǎn)單登錄頁(yè)面
這篇文章主要為大家詳細(xì)介紹了ajax實(shí)現(xiàn)簡(jiǎn)單登錄頁(yè)面,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-06-06

