每60秒更新一次HTML表



我试图使用ajax调用每60秒更新一个flask应用程序上的HTML表。我是flask和jquery的新手,并遵循了类似的stackoverflow问题:Python Flask每60秒刷新一次表

但是我的表没有显示任何数据。

目前我的app.py文件设置如下:

import MySQLdb
import sshtunnel
from datetime import date
import json
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()
query = ("""
SELECT * FROM nfl_data WHERE DATE(nfl_data.date)='{}'
""".format(str(date.today())))
cursor.execute(query)
data = cursor.fetchall()
return json.dumps(data)

和我的nfl_template.html:

<!doctype html>
<html>
<body>
<script>
setInterval(function() {
$.ajax({
type: "GET",
url: "/nfl_data",
})  .done(function( data ) {
console.log(data);
var tableHtml = '';
for (row in data) {
tableHtml += '<tr>';
for (d in row) {
tableHtml += '<td>' + d + '</td>';
}
tableHtml += '</tr>';
}
$("#table-box").html(tableHtml)
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
});
}, 1000 * 60); 
</script>

<table border="2" cellpadding="4" cellspacing="5" id="table-box">
<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>
{% for row in data %}
<tr>
{% for d in row[:-2] %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
</body>
</html>

当我运行应用程序,我得到一个页面只显示表头,但没有数据。我知道SQL查询是正确的,并且正在返回数据,因为我单独测试了它,但是使用ajax请求,我没有得到任何数据显示。

如果我在nfl路由函数内运行SQL查询,并将数据作为参数传递给render_template,数据显示,但它不是每60秒更新一次表。

如果这是您的整个模板,那么问题是您还没有导入jQuery,因此"$"函数不存在。您需要添加:

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

最新更新