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

Flask实时游戏计分系统无法自动更新问题求助

实时游戏计分系统无法同步更新问题排查与修复

核心问题分析

你的代码存在三个关键问题导致无法实时更新:

  1. 后端data_json接口返回硬编码固定数据,即使修改代码里的分数值,不重启服务也不会生效;后续需替换为从数据库读取动态数据。
  2. 前端updateElement函数错误使用score.id匹配DOM元素,但你的数据结构中不存在id字段,应该用user_name(与DOM元素ID的拼接规则一致)。
  3. 前端判断新旧值时未处理渲染空格,可能导致明明值相同却误判为需要更新,同时缺乏元素存在性校验,易触发控制台报错。

修正后代码

后端代码(Flask)

抽离数据获取逻辑,方便后续对接数据库,避免硬编码:

from flask import Flask, jsonify, render_template

app = Flask(__name__)

# 抽离数据获取逻辑,后续可直接替换为MongoDB/Redis查询
def get_score_data():
    # 此处示例为硬编码,实际开发中改为从数据库读取最新数据
    score_data = [
        {
            "user_name": "User 1",
            "country": "India",
            "state": "Karnataka",
            "score": 97
        },
        {
            "user_name": "User 2",
            "country": "India",
            "state": "Karnataka",
            "score": 93
        },
        {
            "user_name": "User 3",
            "country": "United States",
            "state": "New York",
            "score": 85
        },
        {
            "user_name": "User 4",
            "country": "India",
            "state": "New Delhi",
            "score": 80
        }
    ]
    return score_data

@app.route('/data_json')
def data_json():
    score_data = get_score_data()
    return jsonify(score_data)

@app.route('/')
def index():
    score_data = get_score_data()
    return render_template('index.html', scores=score_data)

前端代码(HTML)

修复DOM元素匹配逻辑,增加错误处理:

<table class="table table-dark table-striped">
  <thead>
    <tr>
      <th scope="col">User Name</th>
      <th scope="col">Country</th>
      <th scope="col">State</th>
      <th scope="col">Score</th>
    </tr>
  </thead>
  <tbody id="table_body">
    {% for score in scores %}
    <tr>
        <td id="user_name_{{ score.user_name }}"> {{ score.user_name }}</td>
        <td id="country_{{ score.user_name }}"> {{ score.country }}</td>
        <td id="state_{{ score.user_name }}"> {{ score.state }}</td>
        <td id="score_{{ score.user_name }}"> {{ score.score }}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>
<script>
    setInterval(function() {
            fetch('/data_json')
                .then(response => response.json())
                .then(data => data.forEach(score => updateElement(score)))
                .catch(err => console.error('数据更新失败:', err))
        }, 1000
    );

    function updateElement(score){
        const userName = score.user_name;
        Object.entries(score).forEach(([k,v]) => {
            let element = document.getElementById(`${k}_${userName}`);
            if (!element) return; // 避免元素不存在时报错
            let previousValue = element.innerHTML.trim(); // 去掉渲染空格,避免误判
            if (previousValue !== v.toString()) {
                element.innerHTML = v.toString();
            }
        })
    }
</script>

进阶优化建议

  1. 对接数据库:将get_score_data()改为从MongoDB/Redis读取数据,修改分数时直接更新数据库,实现真正的动态数据来源。
  2. 替换轮询为WebSocket:使用Flask-SocketIO实现服务器主动推送更新,减少不必要的HTTP请求,提升实时性和性能。
  3. 增加数据校验:后端接口返回数据时可添加版本标识,前端仅在版本变化时更新DOM,减少无效渲染。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:43:35