Flask应用通过AJAX每60秒更新HTML表格无数据显示问题求助
问题修复方案
1. 后端app.py修改
首先导入Flask内置的jsonify方法,替换原有的json.dumps返回,自动设置正确的JSON响应头,避免前端拿到纯字符串无法解析:
# 顶部导入新增jsonify from flask import Flask, render_template, jsonify import MySQLdb import sshtunnel from datetime import date app = Flask(__name__) @app.route("/") def home(): return render_template("nfl_template.html") @app.route("/nfl") def nfl(): return render_template("nfl_template.html") @app.route("/nfl_data") def nfl_data(): sshtunnel.SSH_TIMEOUT = 10 sshtunnel.TUNNEL_TIMEOUT = 10 data = [] with sshtunnel.SSHTunnelForwarder( ('ssh.pythonanywhere.com'), ssh_username='USER', ssh_password='***', remote_bind_address=('USER.mysql.pythonanywhere-services.com', 3306) ) as tunnel: connection = MySQLdb.connect( user='USER', passwd='***', host='127.0.0.1', port=tunnel.local_bind_port, db='USER$liveSports', ) cursor = connection.cursor() # 用参数化查询避免SQL注入,不要用字符串拼接 query = "SELECT * FROM nfl_data WHERE DATE(nfl_data.date)=%s" cursor.execute(query, (date.today(),)) data = cursor.fetchall() # 直接用jsonify返回,自动处理响应格式 return jsonify(data)
- 额外优化:替换原有的字符串拼接SQL为参数化查询,避免SQL注入风险。
2. 前端nfl_template.html修改
主要修复4个核心问题:
- 缺失jQuery依赖引入,
$符号未定义导致AJAX无法执行 - 遍历数组逻辑错误,
for...in遍历数组拿到的是索引不是元素本身 - 直接替换整个表格内容,覆盖原有表头
- 页面加载后需要等60秒才第一次执行刷新,初始页面无数据
修改后的完整代码:
<!doctype html> <html> <head> <!-- 引入jQuery依赖 --> <script src="https://cdn.staticfile.org/jquery/3.6.4/jquery.min.js"></script> </head> <body> <table border="2" cellpadding="4" cellspacing="5"> <!-- 表头单独放在thead,更新不覆盖 --> <thead> <tr> <th>Game Date</th> <th>Game Time</th> <th>Team 1</th> <th>Team 2</th> <th>Team 1 Score</th> <th>Team 2 Score</th> <th>Team 1 Odds</th> <th>Team 2 Odds</th> </tr> </thead> <!-- 数据行单独放在tbody,专门用于动态更新 --> <tbody id="table-body"></tbody> </table> <script> // 封装表格刷新函数 function refreshTable() { $.ajax({ type: "GET", url: "/nfl_data", }).done(function(data) { var tableHtml = ''; // 用for...of遍历数组,直接拿到每一行数据 for (const row of data) { tableHtml += '<tr>'; // 取前8个字段和表头对应,输出单元格值 for (let i = 0; i < 8; i++) { tableHtml += '<td>' + row[i] + '</td>'; } tableHtml += '</tr>'; } // 仅替换tbody内容 $("#table-body").html(tableHtml); }).fail(function(jqXHR, textStatus, errorThrown) { console.log("请求异常:", jqXHR, textStatus, errorThrown); }); } // 页面加载完成后立刻执行一次刷新,同时启动定时器 $(function() { refreshTable(); setInterval(refreshTable, 60 * 1000); }); </script> </body> </html>
验证方法
打开浏览器F12控制台,刷新页面查看:
- 无
$ is not defined报错说明jQuery引入成功 - 控制台打印的返回数据有内容说明接口返回正常
- 没有请求报错说明接口调用正常
内容的提问来源于stack exchange,提问作者Redratz
相关产品推荐
相关产品推荐

