動態更新網頁上的 Div
我正在嘗試使用 Flask 和 JavaScript (AJAX) 動態更新網頁。我想在不重繪 頁面的情況下更新兩支球隊的分數(以設定的時間間隔)。我遇到的問題是“updated_score_div.html”頁面中的 div 分數似乎是追加而不是替換“home.html 頁面”中的 div 分數。有沒有辦法避免這種情況?(通過更改 AJAX 代碼或使用 fetch?)理想情況下,我想為網頁上不同 div 的多個團隊執行此操作。
燒瓶代碼:
from flask import Flask, redirect, url_for, render_template, jsonify
app = Flask(__name__)
@app.route("/updated_score_divs", methods = ['POST'])
def updatescoredivs():
teamonescore = '20'
teamtwoscore = '15'
return jsonify('', render_template("updated_score_divs.html", x = teamonescore, y =
teamtwoscore))
@app.route("/")
def homepage():
teamonescore = '00'
teamtwoscore = '00'
return render_template("home.html", x = teamonescore, y = teamtwoscore)
if __name__ == "__main__":
app.run(debug=True)
home.html 代碼:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(function(){
window.setInterval(function(){
loadNewScore()
}, 3000)
function loadNewScore(){
$.ajax({
url: "/updated_score_divs",
type: "POST",
dataType: "json",
success: [code1, code2]
})
}
});
function code1(data){$(teamonescore).replaceWith(data)}
function code2(data){$(teamtwoscore).replaceWith(data)}
</script>
<h1>Home Html</h1>
This is the Team One Score
<div id = "teamonescore">
{{x}}
</div>
This is the Team Two Score
<div id = "teamtwoscore">
{{y}}
</div>
updated_score_divs.html 代碼:
<div id = "teamonescore">
{{x}}
</div>
<div id = "teamtwoscore">
{{y}}
</div>
初始主頁
更新主頁
uj5u.com熱心網友回復:
問題出在你的邏輯上。該函式updatescoredivs為 teamone 和 teamtwo 提供值,并且這兩個值都通過render_template命令輸出到您的模板。這意味著您的模板 -updated_score_divs.html code實際上有 2 個分數。
然后teamonescore用模板替換內容(記住它已經有 2 個值),然后用teamtwoscore相同的模板替換內容。因此,您可以重復模板(因此它看起來像一個附加)
2)
而不是return render_template在函式中做 a updatescoredivs,你應該只回傳jsoneg
return jsonify(x = teamonescore, y = teamtwoscore)
uj5u.com熱心網友回復:
用jquery...
// pass an ElementID and an endpoint to redraw that div with the endpoints response
window.redraw = function( _id, endpoint ){
$.get( endpoint, function( data ) {
$( "#" _id ).html( $(data).html() );
});
}
帶取...
function redraw(_id, endpoint) {
fetch(endpoint)
.then(function(response){return response.text();})
.then(function(data){
document.getElementById(_id).innerHTML = data;
}
)
}
還考慮 htmx 來隱藏所有這些... https://htmx.org/
并且不要回傳json。回傳 html。沒關系。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/338690.html
標籤:javascript Python 阿贾克斯 烧瓶
上一篇:Laravel8中ajax的405(不允許的方法)錯誤
下一篇:Ajax-根據回傳值更改文本顏色
