javascript - 动态更新网页上的 div (flask)
问题描述
动态更新网页上的 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>
解决方案
用 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。没关系。
推荐阅读
- php - PHP Wordpress:将输入的时间存储为 HH:MM:SS.ms
- python - 将数据帧索引值提取到一个 numpy 数组中
- python - Python程序无法读取新行(进入)
- python - 为函数变量分配动态默认值?
- jquery - 更改下面行中带有 jquery 值的输入字段后未定义
- typescript - 打字稿不能通过实例调用类内的函数
- list - 如何将一个列表分成两个列表并找到它们的长度?
- java - 用 IntelliJ IDEA 中的等效方法替换 lambda 表达式
- visual-studio-2019 - 如何保持调试控制台停靠在 Visual Studio 中
- html - 如何让 div 只显示在桌面上?