【Flask-7】前后端数据交互

实现的功能:通过 AJAX(使用 Fetch API)从后端 API 端点获取实时数据,然后将这些数据填充到 HTML 页面的各个元素中。

html伪代码:

复制代码
<div class="data-item">
    <div class="data-label">
        <i class="fas fa-tachometer-alt"></i> 当前速度 (m/s)
    </div>
    <div class="data-value" id="current-speed">0.00</div>
</div>
<div class="data-item">
    <div class="data-label">
        <i class="fas fa-ruler-vertical"></i> 物料高度 (mm)
    </div>
    <div class="data-value" id="material-height">0.00</div>
</div>

js代码:

复制代码
function updateRealtimeData() {
    fetch('/api/realtime-data')
        .then(response => response.json())
        .then(data => {
            document.getElementById('current-speed').textContent = data.current_speed.toFixed(2);
            document.getElementById('material-height').textContent = data.material_height.toFixed(2);
        })
        .catch(error => console.error('Error fetching realtime data:', error));
}


document.addEventListener('DOMContentLoaded', function() {
    // 立即更新一次数据
    updateRealtimeData();

    // 设置定时更新
    setInterval(updateRealtimeData, 1000); // 每秒更新实时数据
});

解析:

复制代码
fetch('/api/realtime-data')
  • 使用 Fetch API 向服务器发起 GET 请求

  • 请求地址为 /api/realtime-data(相对路径).then(response => response.json())

    .then(response => response.json())

  • 第一个 .then() 处理 HTTP 响应

  • 将响应体解析为 JSON 格式

  • 返回一个 Promise,解析后的数据传递给下一个 .then()

app.py伪代码:

复制代码
@app.route('/api/realtime-data')
def get_realtime_data():
    """获取实时数据API"""
    return jsonify(current_data)
相关推荐
数字化转型分享点滴13 小时前
机加工车间上线 SH‑AIOT 物联网会遇到哪些常见实施难点
python·物联网
05664613 小时前
agent学习——流式响应与文本切分
网络·python·学习
OPEN-F13 小时前
Python进阶教程:正则表达式进阶与文本处理
开发语言·python·正则表达式
新网企兴13 小时前
2026年陕西做GEO推广,找新网企兴解决获客难题
python·搜索引擎
青 春 记 忆14 小时前
LeetCode 142. 环形链表 II|Python 解法详解
python·leetcode·链表
for_ever_love__14 小时前
python基础语法学习: 面向对象的三大特性
开发语言·python·学习
Spider赵毅14 小时前
Python爬虫踩坑实录:BeautifulSoup使用中的高频问题排查
爬虫·python·beautifulsoup
怪奇云呼军15 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
悟空瞎说15 小时前
# Alamofire 使用文档 完整翻译
ios
zmzb010316 小时前
Python课后习题训练记录Day194
python·opencv·计算机视觉