You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask框架下如何不刷新全页仅更新网页内指定交易状态表格

完全可以实现,核心是用AJAX异步请求后端接口拿最新数据,局部替换表格内容即可,不需要整页刷新。以下是具体实现步骤:


步骤1:调整Flask后端代码

保留原有页面渲染接口,新增一个专门返回JSON格式交易数据的API接口,同时修正你原有代码里的拼写错误transacions→transactions:

from flask import jsonify

# 原有页面渲染接口保留,只修改拼写错误即可
@app.route('/clientarea')
def clientarea():
    # 你原有登录校验逻辑保持不变
    email = current_user.email # 替换为你自己的获取登录用户邮箱的逻辑
    cursor.execute('Select * from process WHERE email=%s ORDER BY timestamp DESC LIMIT 20', (email,))
    transactions = cursor.fetchall()
    return render_template('clientarea.html', transactions=transactions)

# 新增异步获取交易数据的接口
@app.route('/api/transactions', methods=['GET'])
def get_transactions():
    # 必须加用户身份校验,避免数据泄露,校验逻辑和上面的clientarea接口保持一致
    if not current_user.is_authenticated:
        return jsonify({"error": "未授权访问"}), 403
    email = current_user.email
    cursor.execute('Select * from process WHERE email=%s ORDER BY timestamp DESC LIMIT 20', (email,))
    transactions = cursor.fetchall()
    # 提前格式化日期,减少前端处理逻辑
    res_data = []
    for item in transactions:
        res_data.append({
            "date": item.get('date').strftime("%d %B, %Y"),
            "pcount": item.get('pcount'),
            "pcompleted": item.get('pcompleted'),
            "pfailed": item.get('pfailed')
        })
    return jsonify(res_data)

步骤2:修改前端HTML代码

新增刷新按钮,修正原有HTML里tbody放在循环里重复生成的问题,给tbody加唯一ID方便JS操作:

<!-- 表格上方加刷新按钮 -->
<button id="refreshBtn" class="btn btn-primary mb-2">刷新交易数据</button>

<table class="table table-hover table-bordered table-sm" style="text-align:center">
  <thead>
    <tr>
      <th scope="col" style="width: 25%">Date</th>
      <th scope="col" style="width: 25%">Process Count</th>
      <th scope="col" style="width: 25%">Completed Process</th>
      <th scope="col" style="width: 25%">Failed Process</th>
    </tr>
  </thead>
  <!-- 把tbody移到循环外面,加唯一ID -->
  <tbody id="transactionTbody">
    {% for transaction in transactions %}
    <tr>
      <td>{{ transaction.get('date').strftime("%d %B, %Y") }}</td>
      <td>{{ transaction.get('pcount') }}</td>
      <td>{{ transaction.get('pcompleted') }}</td>
      <td>{{ transaction.get('pfailed') }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

步骤3:添加异步请求逻辑

在页面</body>标签前添加以下JS代码,不需要额外引入依赖,原生JS即可实现:

<script>
document.getElementById('refreshBtn').addEventListener('click', function() {
  // 发送异步请求拿最新数据
  fetch('/api/transactions')
    .then(res => res.json())
    .then(data => {
      const tbody = document.getElementById('transactionTbody');
      // 清空原有表格内容
      tbody.innerHTML = '';
      // 遍历新数据生成新的表格行
      data.forEach(item => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${item.date}</td>
          <td>${item.pcount}</td>
          <td>${item.pcompleted}</td>
          <td>${item.pfailed}</td>
        `;
        tbody.appendChild(tr);
      });
    })
    .catch(err => console.error('数据刷新失败:', err));
});
</script>

补充说明

  • 如果你的项目已经引入了jQuery,可以用$.get方法替换上面的fetch逻辑,写法更简洁
  • 可以给刷新按钮加点击加载状态,避免用户重复点击发送多次请求
  • 接口的身份校验一定要加上,防止他人越权获取数据

内容的提问来源于stack exchange,提问作者Derik0003

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 19:06:04