首页 > 解决方案 > 如何更新烧瓶中网页的特定表格?

问题描述

我正在使用flask 2.0,我的网页上有一个表格显示了交易的状态。实际上,正在通过调用托管在我的服务器中的 MySQL 数据库来更新状态。并且该表格仅在网页完全刷新后才使用最新数据进行更新。当我检查表旁边的刷新按钮时,有没有办法可以调用 MySQL DB 并只更新表?

当前代码和摘录如下所示:

Flask App:

cursor.execute('Select * from process WHERE email=%s ORDER BY timestamp DESC LIMIT 20', (email,))
transactions = cursor.fetchall()
return render_template('clientarea.html', transactions=transacions)

HTML:
<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>
                {% for transaction in transactions %}
              <tbody>
                <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>

              </tbody>
                {% endfor %}
</table>

是否可以在不使用烧瓶刷新页面的情况下加载更新的值?

标签: flask

解决方案


使用 AJAX

将此代码插入html中的head标签

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script>
    $(function () {
        $('#refreshBtn').on('click', function () {
            $.ajax({
                method: 'get',
                url: 'http://localhost:5000/table-refresh',
                dataType: 'json',
                success : function(data){
                    $.each(data, function(val) {
                        $('#date_' + data[val][0]).html(data[val][1]);
                        $('#pcount_' + data[val][0]).html(data[val][2]);
                        $('#pcompleted_' + data[val][0]).html(data[val][3]);
                        $('#pfailed_' + data[val][0]).html(data[val][4]);
                    });
                }
            });
        });
    });
</script>

在表行中授予 id,添加新的刷新按钮

<td id="date_{{ transaction.id }}">{{ transaction.get('date').strftime("%d %B, %Y") }}</td>
<td id="pcount_{{ transaction.id }}">{{ transaction.get('pcount') }}</td>
<td id="pcompleted_{{ transaction.id }}">{{ transaction.get('pcompleted') }}</td>
<td id="pfailed_{{ transaction.id }}">{{ transaction.get('pfailed') }}</td>
<input type="button" id="refreshBtn" value="refresh" />

最后,为刷新表创建新路由器

@app.route('/table-refresh', methods=['GET'])
def table_refresh():
    # [[id, date, pcount, pcompleted, pfailed], ...]
    arr = [[1, '2021-08-23', 1, 1, 1], [2, '2021-08-24', 1, 1, 1]]
    return jsonify(arr)

推荐阅读