【发布时间】:2021-12-06 00:46:11
【问题描述】:
我正在尝试使用 ajax 调用在烧瓶应用程序上每 60 秒更新一次 HTML 表。 我对flask和jquery非常陌生,并遵循了这个类似的stackoverflow问题: Python Flask Refresh table every 60 seconds
但是我的表格没有显示任何数据。
目前我的 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 秒更新一次表。
【问题讨论】:
-
您在控制台中看到您的数据了吗?
-
附注——您每次都在擦除表格标题。
-
没有数据输出到控制台。我应该如何格式化标题,这样它们就不会每次都被删除?我对任何 html 都很陌生。
-
127.0.0.1 - - [18/Oct/2021 22:04:29] "GET /nfl HTTP/1.1" 200 -这是控制台的唯一输出。