flask - 如何更新烧瓶中网页的特定表格?
问题描述
我正在使用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>
是否可以在不使用烧瓶刷新页面的情况下加载更新的值?
解决方案
使用 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)
推荐阅读
- java - Eclipse 控制台未显示标准错误
- c# - 实体框架自动增量
- java - 如何从 Firebase 数据库获取密码并与 edittext 匹配?
- angular - Angular - 如何更改文本输入状态
- javascript - 如果数组中包含 JavaScript/lodash 中的特定字符/字符串,如何消除数组中的值?
- jenkins - 如何限制我的 groovy 脚本仅获取 24 小时/1 天的构建计数,如果我在执行作业时运行它会失败
- xamarin - xamarin 中列表视图的数据绑定
- python - 如何用边连接两个子图?
- python - 使用python发送电子邮件时如何解决身份验证错误
- django - 添加自定义模板后,密码重置电子邮件未发送