You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask+AJAX实现网页div动态更新时内容叠加问题求助

动态更新网页Div内容

可以通过修改AJAX代码解决该问题,核心问题是现有代码存在语法和逻辑错误,和使用AJAX还是fetch接口无关,即便改用fetch不修正逻辑也会出现同样问题。


问题根因

  • jQuery选择器语法错误:选择id元素需要加#前缀,原代码$(teamonescore)无法正确匹配到对应DOM元素
  • AJAX回调配置错误:jQuery的success参数要求传入单个回调函数,原代码传入数组的写法不符合API规范,会导致回调执行异常
  • DOM操作方法使用不当:replaceWith会直接替换整个目标DOM元素,若替换后的新元素没有对应ID,后续定时更新会找不到目标元素
  • 前后端数据结构不匹配:原Flask接口返回的是包含空字符串和完整模板内容的数组,前端两个回调的处理逻辑完全不匹配返回结构

最优修改方案(推荐,方便后续扩展多队伍需求)

直接改后端返回结构化JSON数据,前端直接更新对应div的内部内容,不需要额外的updated_score_divs.html模板文件,扩展性更强。

修改后Flask代码

from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route("/updated_score_divs", methods = ['POST'])
def updatescoredivs():
    # 后续新增多队伍直接在这里加对应的键值对即可
    teamonescore = '20'
    teamtwoscore  = '15'
    return jsonify({
        "teamonescore": teamonescore,
        "teamtwoscore": 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(){
    // 每3秒拉取一次最新分数
    window.setInterval(loadNewScore, 3000)

    function loadNewScore(){
        $.ajax({
            url: "/updated_score_divs",
            type: "POST",
            dataType: "json",
            success: function(data){
                // 替换div内部文本内容,不改动DOM元素本身
                $('#teamonescore').text(data.teamonescore)
                $('#teamtwoscore').text(data.teamtwoscore)
                // 后续新增多队伍直接加一行对应id的赋值即可
            }
        }) 
    }     
});
</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渲染的方式,修改方案如下:

  1. 调整Flask接口返回内容,只返回渲染后的模板字符串:
@app.route("/updated_score_divs", methods = ['POST'])
def updatescoredivs():
    teamonescore = '20'
    teamtwoscore  = '15'
    return render_template("updated_score_divs.html", x = teamonescore, y = teamtwoscore)
  1. 前端AJAX逻辑调整为直接替换对应div内容:
function loadNewScore(){
    $.ajax({
        url: "/updated_score_divs",
        type: "POST",
        success: function(htmlStr){
            const tempDom = $(htmlStr)
            $('#teamonescore').html(tempDom.filter('#teamonescore').html())
            $('#teamtwoscore').html(tempDom.filter('#teamtwoscore').html())
        }
    }) 
}

内容的提问来源于stack exchange,提问作者Patrick B

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:45:07