首页 > 解决方案 > 动态更新网页上的 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>

初始主页
更新主页

标签: javascriptpythonajaxflask

解决方案


用 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。没关系。


推荐阅读