【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)
相关推荐
AI视觉网奇1 小时前
手部检测 yolov5 实战笔记
python·深度学习·计算机视觉
hyswl6661 小时前
数字货物搬家小程序
python·小程序
LDG_AGI1 小时前
【推荐系统】深度学习训练框架(六):PyTorch DDP(DistributedDataParallel)数据并行分布式深度学习原理
人工智能·pytorch·分布式·python·深度学习·算法·spark
背心2块钱包邮1 小时前
第24节——手搓一个“ChatGPT”
人工智能·python·深度学习·自然语言处理·transformer
执笔论英雄1 小时前
【大模型推理】小白教程:vllm 异步接口
前端·数据库·python
databook2 小时前
Manim v0.19.1 发布啦!三大新特性让动画制作更丝滑
后端·python·动效
8***23552 小时前
SQL Server2022版+SSMS安装教程(保姆级)
后端·python·flask
Sally_xy2 小时前
Python 虚拟环境
开发语言·chrome·python
serve the people2 小时前
tensorflow tf.function 的两种执行模式(计算图执行 vs Eager 执行)的关键差异
人工智能·python·tensorflow