四、个人项目体系搭建

[复制链接]
发表于 2025-12-5 19:04:03 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
结果图(打码之后):

一、python写的后端代码

  后端代码利用Flask编写,如下所示:
  1. # app.py
  2. from flask import Flask, render_template, request, jsonify, g
  3. import sqlite3
  4. import os
  5. from datetime import datetime
  6. app = Flask(__name__)
  7. # ----------------------------------------------------------------------------
  8. #   默认配置与默认函数
  9. # ----------------------------------------------------------------------------
  10. connection = 'example.db'          # 连接数据库
  11. @app.route('/')
  12. def index():
  13.     return render_template('index.html')
  14. def get_db():
  15.     if not hasattr(g, 'db'):
  16.         g.db = sqlite3.connect(connection)
  17.         g.db.row_factory = sqlite3.Row  # 将查询结果以字典形式返回
  18.     return g.db
  19. @app.teardown_appcontext
  20. def close_db(error=None):
  21.     """请求结束时关闭数据库连接"""
  22.     if hasattr(g, 'db'):
  23.         g.db.close()
  24. # 返回当前数据库的最大ID,离线函数
  25. def maxID():
  26.     conn1 = get_db()
  27.     cursor = conn1.cursor()
  28.     try:
  29.         cursor.execute("SELECT * FROM projectTable")
  30.         rows = cursor.fetchall()
  31.         ID = []
  32.         for row in rows:
  33.             ID.append(int(row[0]))
  34.         if ID == []:
  35.             ID = [0]
  36.         maxid = max(ID)
  37.         return maxid
  38.     except Exception as e:
  39.         return jsonify({"message": "maxID发生错误"}), 500
  40.     finally:
  41.         # 确保关闭连接
  42.         conn1.close()
  43. # ----------------------------------------------------------------------------
  44. #   获得当前表中所有的项目名称(去重过的)
  45. # ----------------------------------------------------------------------------
  46. @app.route('/projectNameOptions', methods=['POST'])
  47. def projectNameOptions():
  48.     conn = get_db()
  49.     cursor = conn.cursor()
  50. # 表格如果不存在就创建
  51.     print("projectNameOptions正在运行……")
  52.     cursor.execute("SELECT DISTINCT(projectName) FROM projectTable")
  53.     rows = cursor.fetchall()
  54.     results = []
  55.     for row in rows:
  56.         results.append(row['projectName'])
  57.     return jsonify({"projects": results})
  58. # ----------------------------------------------------------------------------
  59. #   前端页面默认返回的数据
  60. # ----------------------------------------------------------------------------
  61. @app.route('/default', methods=['POST'])
  62. def default():
  63.     conn = get_db()
  64.     cursor = conn.cursor()
  65.     # 表格如果不存在就创建
  66.     print("default正在运行……")
  67.     if os.path.exists('example.db'):
  68.         print("Database file exists!")
  69.     else:
  70.         print("Database file does not exist.")
  71.     cursor.execute('''
  72.                 CREATE TABLE IF NOT EXISTS projectTable (
  73.                     id INTEGER PRIMARY KEY AUTOINCREMENT,
  74.                     projectName TEXT,
  75.                     submitPersonName TEXT,
  76.                     Process TEXT,
  77.                     StartTime TEXT,
  78.                     EndTime TEXT,
  79.                     neirong TEXT
  80.                 )
  81.                 ''')
  82.     cursor.execute("SELECT * FROM projectTable")
  83.     rows = cursor.fetchall()
  84.     results = []
  85.     for row in rows:
  86.         results.append({
  87.             'id': row['id'],
  88.             'projectName': row['projectName'],
  89.             'submitPersonName': row['submitPersonName'],
  90.             'Process': row['Process'],
  91.             'StartTime': row['StartTime'],
  92.             'EndTime': row['EndTime'],
  93.             "neirong" : row['neirong']
  94.         })
  95.     print(results)
  96.     return jsonify(results)
  97. # ----------------------------------------------------------------------------
  98. #   根据所给条件(projectname专案名称, personname提交人, projectquery专案进度)查询数据
  99. # ----------------------------------------------------------------------------
  100. @app.route('/searchfor', methods=['POST'])
  101. def searchfor():
  102.     conn = get_db()
  103.     cursor = conn.cursor()
  104.     # 返回的数据
  105.     data = request.get_json()
  106.     print("查询条件 = ", data)
  107.     if data["projectname"] == "":
  108.         projectquery = "projectName LIKE '%'"
  109.     else:
  110.         projectquery = "projectName LIKE '%{}%'".format(data["projectname"])
  111.     if data["personname"] == "":
  112.         personNamequery = "submitPersonName LIKE '%'"
  113.     else:
  114.         personNamequery = "submitPersonName LIKE '%{}%'".format(data["personname"])
  115.     Processquery = "Process LIKE '%{}%'".format(data["stateSelectionValue"])
  116.     print(Processquery)
  117.     query = "SELECT * FROM projectTable WHERE {} AND {} AND {}".format(projectquery, personNamequery, Processquery)
  118.     print("searchFor query:", query)
  119.     cursor.execute(query)
  120.     rows = cursor.fetchall()
  121.     results = []
  122.     for row in rows:
  123.         results.append({
  124.             'id': row['id'],
  125.             'projectName': row['projectName'],
  126.             'submitPersonName': row['submitPersonName'],
  127.             'Process': row['Process'],
  128.             'StartTime': row['StartTime'],
  129.             'EndTime': row['EndTime'],
  130.             "neirong" : row['neirong']
  131.         })
  132.     print("查询结果:", results)
  133.     return jsonify(results)
  134. # ----------------------------------------------------------------------------
  135. #   保存数据
  136. # ----------------------------------------------------------------------------
  137. @app.route('/saveData', methods=['POST'])
  138. def receive_data():
  139.     try:
  140.         conn = get_db()
  141.         cursor = conn.cursor()
  142.         data = request.get_json()
  143.         # 当前更新的时间
  144.         currenttime = datetime.now()
  145.         formatted_time = currenttime.strftime("%Y-%m-%d")
  146.         if data:
  147.             print("收到的表格数据:", data)
  148.             # 启动事务
  149.             for updated_data in data:
  150.                 query = '''
  151.                         UPDATE projectTable
  152.                         SET
  153.                             projectName = ?,
  154.                             neirong = ?,
  155.                             submitPersonName = ?,
  156.                             process = ?,
  157.                             startTime = ?,
  158.                             endTime = ?
  159.                         WHERE id = ?
  160.                     '''
  161.                 cursor.execute(query, (
  162.                     updated_data['projectName'],
  163.                     updated_data['projectNeirong'],
  164.                     updated_data['submitPersonName'],
  165.                     updated_data['process'],
  166.                     updated_data['startTime'],
  167.                     # formatted_time,
  168.                     updated_data['endTime'],
  169.                     updated_data['id']
  170.                 ))
  171.             conn.commit()
  172.             cursor.execute("SELECT * FROM projectTable")
  173.             rows = cursor.fetchall()
  174.             print("查询结果==========================================================")
  175.             for row in rows:
  176.                 print(
  177.                     f"ID: {row[0]}, Project Name: {row[1]}, Submitter: {row[2]}, Process: {row[3]}, Start Time: {row[4]}, End Time: {row[5]}, Neirong: {row[6]}")
  178.             print("已更改!")
  179.             return jsonify({"message": "数据接收成功", "receivedData": data}), 200
  180.     except Exception as e:
  181.         # 如果有任何异常,回滚事务
  182.         conn.rollback()
  183.         print("发生错误:", e)
  184.         return jsonify({"message": "处理数据时发生错误"}), 500
  185.     finally:
  186.         # 确保关闭连接
  187.         conn.close()
  188. # ----------------------------------------------------------------------------
  189. #   删除指定的一行
  190. # ----------------------------------------------------------------------------
  191. @app.route('/delectable', methods=['POST'])
  192. def delete_data():
  193.     conn = get_db()
  194.     cursor = conn.cursor()
  195.     # 返回数据示例:{'id': 1, 'flag': True}
  196.     data = request.get_json()
  197.     if data:
  198.         print("收到的表格数据:", data)
  199.         try:
  200.             if data["flag"]:
  201.                 query = '''
  202.                     DELETE FROM projectTable WHERE id = ?
  203.                 '''
  204.                 # 使用参数化查询
  205.                 cursor.execute(query, (data['id'], ))
  206.             conn.commit()
  207.             cursor.execute("SELECT * FROM projectTable")
  208.             rows = cursor.fetchall()
  209.             print("查询结果==========================================================")
  210.             for row in rows:
  211.                 print(
  212.                     f"ID: {row[0]}, Project Name: {row[1]}, Submitter: {row[2]}, Process: {row[3]}, Start Time: {row[4]}, End Time: {row[5]}, Neirong: {row[6]}")
  213.             print("已删除!")
  214.             return jsonify({"message": "数据接收成功", "receivedData": data}), 200
  215.         except Exception as e:
  216.             # 如果有任何异常,回滚事务
  217.             conn.rollback()
  218.             print("发生错误:", e)
  219.             return jsonify({"message": "处理数据时发生错误"}), 500
  220.         finally:
  221.             # 确保关闭连接
  222.             conn.close()
  223.     else:
  224.         return jsonify({"message": "无效的数据"}), 400
  225. # ----------------------------------------------------------------------------
  226. # 插入一行
  227. # ----------------------------------------------------------------------------
  228. @app.route('/insertTable', methods=['POST'])
  229. def insert_data():
  230.     print("insertTable正在运行!")
  231.     conn = get_db()
  232.     cursor = conn.cursor()
  233.     data = request.get_json()
  234.     print("data = ", data)
  235.     # 获得当前时间
  236.     currenttime = datetime.now()
  237.     formatted_time = currenttime.strftime("%Y-%m-%d")
  238.     try:
  239.         cursor.execute("SELECT MAX(id) FROM projectTable")
  240.         max_id = cursor.fetchone()[0]  # 获取查询结果的第一列
  241.         if max_id is None:
  242.             max_id = 0  # 如果表中没有记录,则最大ID是0
  243.         ids = max_id + 1
  244.         insertData = {'id': ids, 'projectName': '在这里填写专案名称', 'submitPersonName': '',
  245.                       'process': '', 'startTime': '2023-11-10', 'endTime': '2023-11-10', 'projectNeirong': '在这里填写专案内容'}
  246.         insertData["endTime"] = formatted_time
  247.         print(insertData)
  248.         query = '''
  249.                     INSERT INTO projectTable (projectName, neirong, submitPersonName, process, startTime, endTime, id)
  250.                     VALUES (?, ?, ?, ?, ?, ?, ?)
  251.                 '''
  252.         cursor.execute(query, (
  253.             insertData['projectName'],
  254.             insertData['projectNeirong'],
  255.             insertData['submitPersonName'],
  256.             insertData['process'],
  257.             insertData['startTime'],
  258.             insertData['endTime'],
  259.             insertData['id']
  260.         ))
  261.         conn.commit()
  262.         cursor.execute("SELECT * FROM projectTable")
  263.         rows = cursor.fetchall()
  264.         show_data = []
  265.         for row in rows:
  266.             show_data.append({
  267.                 'id': row[0], 'projectName': row[1], 'submitPersonName': row[2],
  268.                 'Process': row[3], 'StartTime': row[4], 'EndTime': row[5],
  269.                 'neirong': row[6]
  270.             })
  271.         print("插入操作已执行!")
  272.         return jsonify({"message": "数据插入成功", "data": show_data})
  273.     except Exception as e:
  274.         return jsonify({"message": "处理数据时发生错误"}), 500
  275.     finally:
  276.         # 确保关闭连接
  277.         conn.close()
  278. # ----------------------------------------------------------------------------
  279. #   主函数
  280. # ----------------------------------------------------------------------------
  281. if __name__ == '__main__':
  282.     app.run(debug=True)
复制代码
二、html代码

  1. <!DOCTYPE html>
  2. <html lang="zh">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>专案管理页面</title>
  7.     <link rel="stylesheet" href="{{ url_for('static', filename='index.css') }}">
  8.     <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  9.     <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
  10.     <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  11.     <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
  12. </head>
  13. <div class="header">
  14.     <h1>专案管理系统</h1>
  15.     <span id="clock"></span>
  16. </div>
  17. <script>
  18.     function updateClock() {
  19.         const now = new Date();
  20.         const hours = String(now.getHours()).padStart(2, '0');
  21.         const minutes = String(now.getMinutes()).padStart(2, '0');
  22.         const seconds = String(now.getSeconds()).padStart(2, '0');
  23.         const currentTime = `${hours}:${minutes}:${seconds}`;
  24.         document.getElementById('clock').textContent = currentTime;
  25.     }
  26.    
  27.     setInterval(updateClock, 1000);
  28.     updateClock(); // Initialize the clock immediately
  29. </script>
  30. <div class="container">
  31.     <div class="form-container" id="login-form">
  32.         <form id="projectForm" action="/" method="POST">
  33.             <!-- 把专案名称更换为 -->
  34.             <label for="projectname">专案名称:</label>
  35.             <select id="projectname" name="projectname">
  36.                     <!-- 选项由JS动态添加 -->
  37.             </select>
  38.             <!-- <label for="projectname">专案名称:</label>
  39.             <input type="text" id="projectname" name="projectname"> -->
  40.             <label for="personname">提交人:</label>
  41.             <input type="text" id="personname" name="personname">
  42.             <label for="stateSelection">专案状态:</label>
  43.             <select id="stateSelection" name="stateSelection">
  44.                     <option value=""></option>
  45.                     <option value="Ongoing">正在进行</option>
  46.                     <option value="shunyan">顺延(本周无进度)</option>
  47.                     <option value="achieved">已经完成</option>
  48.             </select>
  49.             <button id="addRowBtn" type="button">增加一行</button>          <!-- 添加按钮-->
  50.             <button type="submit">查询</button>
  51.             <button type="button" onclick="clearFormat()">清除格式</button>         
  52.         </form>
  53.     </div>
  54.     <div class="assiantFre_container">
  55.         <table id="projectTable">
  56.             <thead id="tableHeader">
  57.             <!-- 动态生成的表头将插入这里 -->
  58.             </thead>
  59.             <tbody id="tableBody">
  60.             <!-- 动态生成的表格数据将插入这里 -->
  61.             </tbody>
  62.         </table>
  63.     </div>
  64.     <script src="{{ url_for('static', filename='index.js') }}"></script>
  65. </div>
  66. </html>
复制代码
三、index.css

  1. /* styles.css */
  2. /* 基本样式重置 */
  3. * {
  4.     margin: 0;
  5.     padding: 0;
  6.     box-sizing: border-box;
  7. }
  8. /* h1 {
  9.     text-align: center;
  10.     margin-bottom: 20px;
  11.     color: #444;
  12. } */
  13. .header {
  14.     display: flex;
  15.     justify-content: space-between;
  16.     /* 将内容两端对齐 */
  17.     align-items: center;
  18.     /* 垂直居中对齐 */
  19.     padding: 20px;
  20.     /* 添加内边距 */
  21.     background-color: #f8f8f8;
  22.     /* 背景颜色 */
  23. }
  24. .header h1 {
  25.     margin: 0 auto;
  26.     /* 使标题居中 */
  27. }
  28. .header #clock {
  29.     font-size: 24px;
  30.     margin-left: 120px;
  31.     color: white; /* 设置文字颜色 */
  32.     background-color: #343a40; /* 设置背景颜色 */
  33.     padding: 10px 20px; /* 添加内边距 */
  34.     border-radius: 5px; /* 添加圆角 */
  35.     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影 */
  36.     background: linear-gradient(135deg, #4285f4, #673ab7);
  37.     animation: blink 1s infinite alternate; /* 添加闪烁动画 */
  38. }
  39. @keyframes blink {
  40.     from {
  41.         opacity: 1;
  42.     }
  43.     to {
  44.         opacity: 0.5;
  45.     }
  46. }
  47. .container {
  48.     font-family: Arial, sans-serif;
  49.     background-color: #f4f4f4;
  50.     color: #333;
  51.     line-height: 1.6;
  52.     padding: 20px;
  53.     border-radius: 8px;
  54.     box-shadow: 0 0 1px rgba(0, 0, 0, 0.1);
  55. }
  56. .form-container {
  57.     display: flex;
  58.     /* 使用 Flexbox 布局 */
  59.     align-items: center;
  60.     /* 垂直居中对齐 */
  61.     justify-content: flex-start;
  62.     /* 控制子元素在容器内的水平排列方式 */
  63.     gap: 20px;
  64.     /* 控制每个控件之间的间距 */
  65. }
  66. form {
  67.     display: flex;
  68.     /* 使表单内的控件排列在一行 */
  69.     gap: 20px;
  70.     /* 控制控件之间的间距 */
  71.     align-items: center;
  72.     /* 垂直对齐控件 */
  73. }
  74. #projectname {
  75.     padding: 10px;
  76.     /* 设置内边距,让内容不与边框紧贴 */
  77.     border: 1px solid #ccc;
  78.     /* 设置边框颜色和样式 */
  79.     border-radius: 4px;
  80.     /* 设置圆角效果 */
  81.     font-size: 16px;
  82.     /* 设置字体大小 */
  83.     width: 200px;
  84.     /* 设置宽度为 200px */
  85.     height: 40px;
  86.     /* 设置高度为 40px */
  87.     background-color: #fff;
  88.     /* 设置背景颜色为白色 */
  89. }
  90. #projectname option {
  91.     padding: 8px;
  92.     /* 设置选项的内边距,避免文字与边缘过于紧密 */
  93. }
  94. /* #projectname {
  95.     width: 200px;  /* 设置宽度 */
  96. /* height: 40px;  设置高度} */
  97. */ label {
  98.     font-weight: bold;
  99.     color: #555;
  100.     margin: 0;
  101.     /* 去掉默认的 margin */
  102. }
  103. input[type="text"] {
  104.     padding: 10px;
  105.     border: 1px solid #ccc;
  106.     border-radius: 4px;
  107.     font-size: 16px;
  108.     width: 200px;
  109.     /* 你可以调整输入框的宽度 */
  110. }
  111. #stateSelection {
  112.     padding: 10px;
  113.     /* 设置内边距,让内容不与边框紧贴 */
  114.     border: 1px solid #ccc;
  115.     /* 设置边框颜色和样式 */
  116.     border-radius: 4px;
  117.     /* 设置圆角效果 */
  118.     font-size: 16px;
  119.     /* 设置字体大小 */
  120.     width: 200px;
  121.     /* 设置宽度为 200px */
  122.     height: 40px;
  123.     /* 设置高度为 40px */
  124.     background-color: #fff;
  125.     /* 设置背景颜色为白色 */
  126. }
  127. #stateSelection option {
  128.     padding: 8px;
  129.     /* 设置选项的内边距,避免文字与边缘过于紧密 */
  130. }
  131. button {
  132.     width: 100px;
  133.     padding: 10px;
  134.     background-color: #007bff;
  135.     color: #fff;
  136.     border: none;
  137.     border-radius: 4px;
  138.     font-size: 16px;
  139.     cursor: pointer;
  140.     transition: background-color 0.3s ease;
  141. }
  142. .assiantFre_container {
  143.     color: #333;
  144.     padding: 20px;
  145.     /* 上下之间的距离 */
  146.     border-radius: 8px;
  147.     font-size: 20px;
  148.     max-width: 100%;
  149.     /* 修改最大宽度为100% */
  150.     width: 100%;
  151. }
  152. table {
  153.     width: 100%;
  154.     /* 设置表格占据100%宽度 */
  155.     border-collapse: collapse;
  156.     /* 合并表格边框 */
  157.     margin-top: 30px;
  158.     /* 设置表格与上方元素的间距 */
  159. }
  160. table th,
  161. table td {
  162.     padding: 12px 15px;
  163.     text-align: left;
  164.     border: 1px solid #ddd;
  165.     /* 为表头和单元格添加边框 */
  166.     word-wrap: break-word;
  167.     /* 自动换行,避免内容溢出 */
  168.     white-space: normal;
  169.     /* 允许正常换行 */
  170. }
  171. table th {
  172.     background-color: #f2f2f2;
  173.     font-weight: bold;
  174.     color: #444;
  175. }
  176. table tr:nth-child(even) {
  177.     background-color: #f9f9f9;
  178. }
  179. table tr:hover {
  180.     background-color: #e9e9e9;
  181. }
复制代码
四、js代码

  1. console.log("index.js 文件已加载");
  2. document.addEventListener('DOMContentLoaded', function () {
  3.     /*********************************************
  4.         获取表单和表格元素
  5.     *********************************************/
  6.     const form = document.getElementById('projectForm');
  7.     const tableHeader = document.getElementById('tableHeader');
  8.     const tableBody = document.getElementById('tableBody');
  9.     const addRowbtn = document.getElementById('addRowBtn');
  10.     /*********************************************
  11.         创建单元格的函数
  12.     *********************************************/
  13.     function createTableCell(content) {
  14.         const td = document.createElement('td');
  15.         td.textContent = content;  // 设置单元格的文本内容
  16.         td.setAttribute('contenteditable', 'true');  // 设置单元格可编辑
  17.         return td;
  18.     }
  19.     /*********************************************
  20.         控制显示表格的函数
  21.     *********************************************/
  22.     function populateTable(data) {
  23.         tableHeader.innerHTML = `
  24.             <tr>
  25.                 <th>ID</th>
  26.                 <th>专案名称</th>
  27.                 <th>专案内容</th>
  28.                 <th>提交人</th>
  29.                 <th>状态</th>
  30.                 <th>项目起始日期</th>
  31.                 <th>更改时间</th>
  32.                 <th>操作</th> <!-- 用于显示删除按钮 -->
  33.             </tr>
  34.         `;
  35.         data.forEach(function (row) {
  36.             const tr = document.createElement('tr');  // 创建一行
  37.             // console.log("row_neirong", row.neirong)
  38.             const createTableCell = (content) => {
  39.                 const td = document.createElement('td');
  40.                 td.innerHTML = content;  // 使用 innerHTML 插入带有 HTML 标签的内容
  41.                 td.contentEditable = true;  // 确保单元格是可编辑的
  42.                 return td;
  43.             };
  44.             tr.appendChild(createTableCell(row.id));
  45.             tr.appendChild(createTableCell(row.projectName));
  46.             tr.appendChild(createTableCell(row.neirong));
  47.             tr.appendChild(createTableCell(row.submitPersonName));
  48.             tr.appendChild(createTableCell(row.Process));
  49.             tr.appendChild(createTableCell(row.StartTime));
  50.             tr.appendChild(createTableCell(row.EndTime));
  51.             // 创建删除按钮的单元格
  52.             const deleteCell = document.createElement('td');
  53.             const deleteButton = document.createElement('button');
  54.             deleteButton.textContent = '删除'; // 设置按钮文本
  55.             deleteButton.classList.add('delete-btn'); // 添加样式类,可以自定义按钮样式
  56.             // 为删除按钮绑定点击事件,删除当前行
  57.             deleteButton.addEventListener('click', function (event) {
  58.                 event.preventDefault();
  59.                 const confirmDelete = window.confirm('是否确定删除这一行?');
  60.                 if (confirmDelete) {
  61.                     const tr = deleteButton.closest('tr');  // 获取当前按钮所在的行
  62.                     const id = tr.querySelector('td:nth-child(1)').textContent.trim()
  63.                     console.log(id)
  64.                     const deleteData = { 'flag': true, 'id': id }
  65.                     tr.remove();  // 删除该行
  66.                     fetch('/delectable', {
  67.                         method: 'POST',
  68.                         headers: {
  69.                             'Content-Type': 'application/json'
  70.                         },
  71.                         body: JSON.stringify(deleteData)
  72.                     })
  73.                         .then(response => response.json())
  74.                         .then(data => {
  75.                             console.log('成功发送数据到delete接口:', data);
  76.                         })
  77.                         .catch(error => {
  78.                             console.error('失败发送数据到delete接口:', error);
  79.                         });
  80.                 }
  81.             });
  82.             deleteCell.appendChild(deleteButton);  // 将按钮添加到单元格中
  83.             tr.appendChild(deleteCell);  // 将单元格添加到行中
  84.             tableBody.appendChild(tr);  // 将完整的行添加到表格主体
  85.         });
  86.     }
  87.     /*********************************************
  88.         默认显示当前表中的数据
  89.     *********************************************/
  90.     fetch('/default', {
  91.         method: 'POST',
  92.         headers: {
  93.             'Content-Type': 'application/json'
  94.         },
  95.     })
  96.         .then(response => response.json())  // 解析返回的 JSON 数据
  97.         .then(data => {
  98.             const defaultData = data;
  99.             // 初始化表格
  100.             console.log(defaultData)
  101.             populateTable(defaultData);
  102.         }).catch(error => {
  103.             console.error('Error:', error);
  104.         });
  105.     /*********************************************
  106.         筛选条件接口
  107.     *********************************************/
  108.     fetch('/projectNameOptions', {
  109.         method: 'POST',
  110.         headers: {
  111.             'Content-Type': 'application/json'
  112.         },
  113.     })
  114.         .then(response => {
  115.             if (!response.ok) {
  116.                 throw new Error('网络响应不正常');
  117.             }
  118.             return response.json();
  119.         })
  120.         .then(data => {
  121.             let exeuted = false
  122.             console.log("正在查询")
  123.             const selectElement = document.querySelector('select[id="projectname"]'); // 使用 id 属性选择器
  124.             // 添加默认选项
  125.             const defaultOption = document.createElement('option');
  126.             defaultOption.value = "";
  127.             defaultOption.textContent = "请选择项目";
  128.             selectElement.appendChild(defaultOption);
  129.             data.projects.forEach(projectName => {
  130.                 const option = document.createElement('option');
  131.                 option.value = projectName;
  132.                 option.textContent = projectName;        //
  133.                 selectElement.appendChild(option);       //
  134.             });
  135.             // 监听 select 元素的 change 事件
  136.             selectElement.addEventListener('change', function () {
  137.                 const SelectedProjectname = selectElement.value;  // 获取当前选中的值
  138.                 console.log('当前选中的项目名称:', SelectedProjectname);
  139.                 search(SelectedProjectname);  // 调用 search 函数并传递选中的值
  140.                 exeuted = true
  141.             });
  142.             if (!exeuted){
  143.                 search(defaultOption.value)
  144.             }
  145.         })
  146.         .catch(error => {
  147.             console.error(error);
  148.         });
  149.     function search(SelectedProjectname) {
  150.         // 查询
  151.         if (form) {
  152.             form.addEventListener('submit', function (event) {
  153.                 event.preventDefault();
  154.                 console.log("查询表单已提交", SelectedProjectname);
  155.                 const projectName = SelectedProjectname
  156.                 const personname = document.getElementById('personname').value;
  157.                 const stateSelectionValue = document.getElementById('stateSelection').value;
  158.                 const formData = {
  159.                     projectname: projectName,  // 获取专案名称
  160.                     personname: personname,   // 获取提交人
  161.                     stateSelectionValue: stateSelectionValue       // 获取专案进度
  162.                 };
  163.                 // 将对象转换为 JSON 字符串
  164.                 const JsonData = JSON.stringify(formData);
  165.                 console.log("JsonData:", JsonData);
  166.                 fetch('/searchfor', {
  167.                     method: 'POST',
  168.                     headers: {
  169.                         'Content-Type': 'application/json',  // 设置请求的内容类型为 JSON
  170.                     },
  171.                     body: JsonData
  172.                 })
  173.                     .then(response => response.json())  // 解析响应的 JSON 数据
  174.                     .then(data => {
  175.                         console.log("searchfor被触发!!");  // 处理接收到的数据
  176.                         console.log('searchfordata:', data);  // 处理接收到的数据
  177.                         // 模拟查询结果
  178.                         const queryResult = data
  179.                         tableHeader.innerHTML = ''
  180.                         tableBody.innerHTML = ''
  181.                         // 显示表格
  182.                         populateTable(queryResult);
  183.                     })
  184.                     .catch(error => {
  185.                         console.error('发送数据时发生错误:', error);  // 错误处理
  186.                     });
  187.             })
  188.         }
  189.         else
  190.             console.log("不存在form!")
  191.     }
  192.     /*********************************************
  193.         插入一行
  194.     *********************************************/
  195.     addRowbtn.addEventListener('click', function () {
  196.         event.preventDefault();
  197.         console.log("click提交事件被触发了");
  198.         fetch('/insertTable', {
  199.             method: 'POST',
  200.             headers: {
  201.                 'Content-Type': 'application/json',  // 设置请求的内容类型为 JSON
  202.             },
  203.             body: JSON.stringify({
  204.                 name: 'John Doe',
  205.                 age: 30,
  206.             })
  207.         })
  208.             .then(response => response.json())  // 解析响应的 JSON 数据
  209.             .then(data => {
  210.                 const newData = data['data'];  // 想要插入的新数据
  211.                 console.log('newdata:', newData);  // 处理接收到的数据
  212.                 tableHeader.innerHTML = ''
  213.                 tableBody.innerHTML = ''
  214.                 // 填充表格
  215.                 populateTable(newData);
  216.             })
  217.             .catch(error => {
  218.                 console.error('发送数据时发生错误:', error);  // 错误处理
  219.             });
  220.     });
  221.     /*********************************************
  222.         保存当前表格到数据库
  223.     *********************************************/
  224.     window.addEventListener('keydown', function (event) {
  225.         // 检查是否按下了 Ctrl + S
  226.         if (event.ctrlKey && event.key === 's') {
  227.             // 阻止默认行为(防止浏览器弹出保存对话框)
  228.             event.preventDefault();
  229.             console.log("表格信息已保存!");
  230.             const jsonData = getTableDataAsJson(tableBody)              // 从页面上获得当前所有的项目
  231.             console.log(jsonData)
  232.             if (jsonData === '[]' || jsonData.length === 0) {
  233.                 console.log("jsonData 是空的");
  234.             } else {
  235.                 console.log("jsonData 不是空的");
  236.                 fetch('/saveData', {
  237.                     method: 'POST',
  238.                     headers: {
  239.                         'Content-Type': 'application/json'
  240.                     },
  241.                     body: jsonData
  242.                 })
  243.                     .then(response => response.json())
  244.                     .then(data => {
  245.                         console.log('成功发送数据到后端:', data);
  246.                     })
  247.                     .catch(error => {
  248.                         console.error('发送数据失败:', error);
  249.                     });
  250.             }
  251.         }
  252.     });
  253.     function getTableDataAsJson(tableBody) {
  254.         const rows = tableBody.querySelectorAll('tr');  // 获取所有的行
  255.         const tableData = [];
  256.         rows.forEach(function (row) {
  257.             const cells = row.querySelectorAll('td');  // 获取每一行的所有单元格
  258.             if (cells.length === 0) return;             // 如果这一行是空的,则跳过
  259.             const rowData = {
  260.                 id: cells[0].textContent.trim(),
  261.                 projectName: cells[1].textContent.trim(),
  262.                 projectNeirong: cells[2].innerHTML.trim(),
  263.                 submitPersonName: cells[3].textContent.trim(),
  264.                 process: cells[4].textContent.trim(),
  265.                 startTime: cells[5].textContent.trim(),
  266.                 endTime: cells[6].textContent.trim()
  267.             };
  268.             tableData.push(rowData);  // 将每一行的数据添加到数组中
  269.         });
  270.         // 将数组转换为 JSON 格式并返回
  271.         return JSON.stringify(tableData);
  272.     }
  273. });
  274. function clearFormat() {
  275.     var table = document.getElementById('projectTable');
  276.     var selection = window.getSelection();
  277.     var selectedText = selection.toString();
  278.     if (selectedText.length === 0) {
  279.         alert("请先选择要清除格式的文本。");
  280.         return;
  281.     }
  282.     // 获取选中的范围
  283.     var range = selection.getRangeAt(0);
  284.     var startContainer = range.startContainer;
  285.     var endContainer = range.endContainer;
  286.     // 创建一个新的文本节点,替换选中的内容
  287.     var plainText = selectedText.replace(/<[^>]*>/g, '');
  288.     var textNode = document.createTextNode(plainText);
  289.     // 替换选中的内容
  290.     range.deleteContents();
  291.     range.insertNode(textNode);
  292.     // 重新设置选中的范围
  293.     range.setStart(textNode, 0);
  294.     range.setEnd(textNode, plainText.length);
  295.     selection.removeAllRanges();
  296.     selection.addRange(range);
  297. }
复制代码
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表