【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)
相关推荐
weixin_4215850111 分钟前
解释代码:val_pred = vxm_model.predict(val_input)--与tensor对比
python
xwill*16 分钟前
python 字符串拼接
linux·windows·python
superman超哥29 分钟前
仓颉锁竞争优化深度解析
c语言·开发语言·c++·python·仓颉
一晌小贪欢31 分钟前
【Python办公自动化】Python办公自动化常用库新手指南
开发语言·python·python自动化办公·python3·python办公自动化·python办公
其美杰布-富贵-李1 小时前
Python 反射完整学习笔记
笔记·python·学习·反射
热心市民小刘05051 小时前
12.23二叉树的层序遍历
python
yaoh.wang1 小时前
力扣(LeetCode) 111: 二叉树的最小深度 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·深度优先
HealthScience1 小时前
怎么搜索某个已知的药物的smiles
python
jimmyleeee1 小时前
人工智能基础知识笔记二十八:几款有用的LLM管理工具
人工智能·笔记·python
schinber1 小时前
Python包管理工具全景指南:从pip到现代化工具实战
python·conda·pip·uv