我正在嘗試使用 ajax 呼叫在燒瓶應用程式上每 60 秒更新一次 HTML 表。我對Flask和 jquery 很陌生,并遵循了這個類似的計算器溢位問題: 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 秒更新一次表。
uj5u.com熱心網友回復:
如果這實際上是您的整個模板,那么問題在于您沒有匯入 jQuery,因此“$”函式不存在。您需要添加:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324097.html
下一篇:關閉已打開的Excel視窗VBA
