網(wǎng)站首頁 編程語言 正文
遇到的小坑
- 回調(diào)函數(shù)相對window.onload的擺放位置
- 給回調(diào)函數(shù)addData傳數(shù)據(jù)時,如何操作才能將數(shù)據(jù)傳進去
代碼實現(xiàn)
前端代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax實現(xiàn)關鍵字聯(lián)想和自動補全</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. 當用戶在文本框里輸入數(shù)據(jù)時,發(fā)生keyup事件時,將文本框里的數(shù)據(jù),以ajax請求方式提交的到后端
3. 后端對前端提交的關鍵字,在數(shù)據(jù)庫里進行模糊查詢
4. 將后端查詢到的數(shù)據(jù)以json格式傳給前端
5. 前端解析后端傳來的數(shù)據(jù),將數(shù)據(jù)顯示在提示欄里
6. 當用戶點擊提示中的某條提示信息時,將提示欄里的信息賦給輸入框,隱藏提示層
注意:1. 凡是輸入框里發(fā)生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時,發(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標簽綁定單擊事件,將數(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){
//完成自動補全
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");
//連接數(shù)據(jù)庫,進行模糊查詢
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);
}
//后端數(shù)據(jù)json化
String jsonKeyWordsArray = JSON.toJSONString(keyWordsList);
//返回后端數(shù)據(jù)
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);
}
}
}
}
數(shù)據(jù)庫表:
一張表: tb_search
數(shù)據(jù)表描述: 除了id, 就一個字段 content varchar(255) not null
效果展示:
自己在遠程數(shù)據(jù)庫上用docker運行了一個mysql數(shù)據(jù)庫,查詢速度比較慢,但演示關鍵字聯(lián)想和自動補全功能的測試目的已經(jīng)達到
原文鏈接:https://www.cnblogs.com/nefu-wangxun/p/16493414.html
相關推薦
- 2022-12-08 linux服務器中搭建redis6.0.7集群_Redis
- 2023-10-10 Promise同時獲取n個接口數(shù)據(jù)的幾種方式
- 2022-06-13 Docker四種網(wǎng)絡模式演示及連通性測試_docker
- 2022-02-10 MongoDB數(shù)據(jù)庫安裝部署及警告優(yōu)化_MongoDB
- 2022-11-23 Golang?官方依賴注入工具wire示例詳解_Golang
- 2022-05-10 手寫Promise中all、race、any方法
- 2022-07-08 Python如何讀取csv文件時添加表頭/列名_python
- 2022-11-24 React?hooks使用方法全面匯總_React
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支