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

如何从Flask网页获取数据并实现跨页面按钮颜色根据状态动态修改?

解决方案:Flask网页间通信并动态修改按钮颜色

嘿,这个需求其实很常见,核心思路是让控制按钮的页面通过AJAX定时请求Flask后端的API接口,获取温度/状态数据,然后根据返回值动态修改按钮样式。我给你分步骤写具体代码,亲测好用:

第一步:给Flask后端添加状态API端点

首先你需要在Flask应用里加一个API路由,专门用来返回温度和状态信息。这样其他页面就能通过HTTP请求拿到数据了。

比如你的app.py可以这么写:

from flask import Flask, jsonify, render_template
import random  # 这里用随机数模拟温度数据,实际替换成你的温度获取逻辑

app = Flask(__name__)

# 模拟温度获取函数
def get_temperature():
    # 实际场景中替换成读取传感器或数据库的代码
    return round(random.uniform(20.0, 35.0), 1)

# 温度显示页面(你的原有页面)
@app.route('/temperature')
def temperature_page():
    temp = get_temperature()
    return render_template('temperature.html', temperature=temp)

# 新增的状态API,供按钮页面调用
@app.route('/api/status')
def get_status():
    temp = get_temperature()
    # 定义状态规则:比如温度>30为异常,否则正常
    status = "error" if temp > 30 else "normal"
    return jsonify({
        "temperature": temp,
        "status": status
    })

if __name__ == '__main__':
    app.run(debug=True)

第二步:制作控制按钮的页面

接下来是那个包含按钮的页面(比如button_page.html),我们用JavaScript定时请求上面的API,根据返回的status来修改按钮颜色。

<!DOCTYPE html>
<html>
<head>
    <title>控制页面</title>
    <style>
        .btn-control {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .btn-normal {
            background-color: #4CAF50; /* 绿色:正常状态 */
            color: white;
        }
        .btn-error {
            background-color: #f44336; /* 红色:异常状态 */
            color: white;
        }
        .btn-offline {
            background-color: #9E9E9E; /* 灰色:请求失败 */
            color: white;
        }
    </style>
</head>
<body>
    <button id="openTempPage" class="btn-control btn-normal">打开温度页面</button>

    <script>
        const btn = document.getElementById('openTempPage');

        // 点击按钮打开温度页面
        btn.addEventListener('click', () => {
            window.open('/temperature', '_blank');
        });

        // 定时请求状态API,比如每3秒更新一次
        function updateButtonStatus() {
            fetch('/api/status')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('请求失败');
                    }
                    return response.json();
                })
                .then(data => {
                    // 根据状态切换按钮样式
                    if (data.status === 'normal') {
                        btn.className = 'btn-control btn-normal';
                        btn.textContent = `打开温度页面(当前温度:${data.temperature}℃)`;
                    } else if (data.status === 'error') {
                        btn.className = 'btn-control btn-error';
                        btn.textContent = `打开温度页面(温度过高:${data.temperature}℃)`;
                    }
                })
                .catch(error => {
                    // 请求失败时的处理
                    btn.className = 'btn-control btn-offline';
                    btn.textContent = '温度页面不可用';
                    console.error('获取状态失败:', error);
                });
        }

        // 页面加载时先执行一次,然后每3秒更新
        updateButtonStatus();
        setInterval(updateButtonStatus, 3000);
    </script>
</body>
</html>

第三步:温度显示页面(temperature.html)

这个是你原有的页面,简单展示温度就行:

<!DOCTYPE html>
<html>
<head>
    <title>温度监控</title>
</head>
<body>
    <h1>当前温度:{{ temperature }}℃</h1>
</body>
</html>

关键说明:

  • 为什么用API而不是直接页面通信?因为浏览器的同源策略限制,跨页面直接通信(比如localStorage、Broadcast Channel)虽然可行,但API方式更稳定,尤其是在页面可能部署在不同路径甚至子域名的场景下。
  • 定时请求的间隔可以根据你的需求调整,比如把3000改成10000就是10秒更新一次。
  • 你可以根据实际需求修改状态判断逻辑,比如不仅看温度,还可以加入其他错误状态(比如传感器离线),只需要在/api/status里返回对应的status即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 06:51:09