【发布时间】:2021-10-26 10:44:43
【问题描述】:
动态更新网页上的 div
我正在尝试使用烧瓶和 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>
【问题讨论】:
标签: javascript python ajax flask