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

Flask中如何每10秒更新HTML模板td标签内的plazas变量值?

解决Flask前端定时更新车位数据的问题

现有代码的问题

后端Flask视图的问题

  • 视图中的while True循环完全无效:第一次执行流程就会走到return render_template,直接返回页面,循环根本不会重复执行
  • Token判断逻辑错误:if(token!='null' or token!='')永远为真,应该使用and来判断token不为空且不为'null'
  • 变量plazas未初始化:如果首次获取Token失败,plazas未定义就返回会直接抛出错误
  • 异常处理里的time.sleep(secs)不在循环范围内,无法实现失败后的重试延迟

前端JavaScript的问题

  • refresh函数的places参数没有传入实际值,导致places未定义
  • 循环结束后执行return elements[i].innerHTML = places会报错,此时i等于elements.length,超出数组索引范围
  • 没有从后端获取最新的plazas数据,仅试图修改DOM但没有有效数据源

解决方案

1. 修复并重构后端代码

修改首页视图只负责渲染初始页面,新增API接口专门返回最新的车位数据:

from flask import jsonify

# 首页视图:渲染初始页面,获取初始数据
@views.route('/')
def home():
    plazas = 0  # 初始化默认值
    totalplazas = 0  # 替换为实际获取总车位的逻辑
    parkings = []  # 替换为实际获取停车场列表的逻辑
    try:
        token = getToken()
        if token and token != 'null':
            plazas = getInfo(token, id)
            # 补充获取totalplazas、parkings的逻辑
            # totalplazas = ...
            # parkings = ...
    except Exception as e:
        print(f'连接失败: {e}')
    
    return render_template("home.html", plazas=plazas, totalplazas=totalplazas, parkings=parkings)

# 新增API接口:返回最新车位数据
@views.route('/api/plazas')
def get_plazas_api():
    plazas = 0
    totalplazas = 0  # 替换为实际获取总车位的逻辑
    try:
        token = getToken()
        if token and token != 'null':
            plazas = getInfo(token, id)
            # 补充获取totalplazas的逻辑
            # totalplazas = ...
    except Exception as e:
        print(f'连接失败: {e}')
    return jsonify({'plazas': plazas, 'totalplazas': totalplazas})

2. 修改前端JavaScript,通过AJAX定时更新数据

替换原有JS代码,实现定时请求API获取最新数据,并同步更新DOM和颜色逻辑:

<script type="text/javascript">
function updatePlazas() {
    fetch('/api/plazas')
        .then(response => response.json())
        .then(data => {
            const plazas = data.plazas;
            const totalplazas = data.totalplazas;
            const elements = document.getElementsByClassName("num");
            
            for(let i = 0; i < elements.length; i++) {
                const element = elements[i];
                // 复刻后端的颜色判断逻辑
                if (parseInt(plazas) >= (totalplazas * 30)/100) {
                    element.style.color = "#39FF00";
                    element.innerHTML = plazas;
                } else if (parseInt(plazas) < 1) {
                    element.style.color = "red";
                    element.innerHTML = '<p class="an">COMPLETO</p>';
                } else if (parseInt(plazas) <= (totalplazas * 10)/100) {
                    element.style.color = "red";
                    element.innerHTML = plazas;
                } else {
                    element.style.color = "yellow";
                    element.innerHTML = plazas;
                }
            }
        })
        .catch(error => {
            console.error('获取数据失败:', error);
        });
}

// 页面加载后立即执行一次,之后每10秒更新一次
window.onload = function() {
    updatePlazas();
    setInterval(updatePlazas, 10000);
};
</script>

3. 模板保持原有逻辑(可选)

原有模板的初始渲染逻辑可以保留,确保页面加载时显示初始车位数据,后续由JS接管更新:

{% for parking in parkings %}
<tr>
    <td class="par"><img src={{parking.image}} alt="img"></td>
    <td class="nombre">{{parking.nombre}}</td>
    {% if plazas|int >= (totalplazas*30)/100 %}
    <td class="num" style="color:#39FF00">
    {{plazas}}</td>
    {% elif plazas|int < 1%}
    <td class="num" style="color:red"><p class="an">COMPLETO</p></td>
    {% elif plazas|int <= (totalplazas*10)/100%}
    <td class="num" style="color:red">
    {{plazas}}</td>
    {% else %}
    <td class="num" style="color:yellow">
    {{plazas}}</td>
    {% endif %}
    <td class="dir"><img src={{parking.direccion}} alt="img"></td>
</tr>
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:35:18