【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)
相关推荐
weixin199701080165 分钟前
“迷你京东”全栈架构设计与实现
java·大数据·python·数据库架构
虚幻如影15 分钟前
Tesseract-OCR 引擎安装
python·ocr
带娃的IT创业者18 分钟前
国内主流大模型API调用入门与对比:DeepSeek/智谱GLM/Kimi/千问完整指南
python·大模型·api调用·kimi·千问·deepseek·智谱glm
一招定胜负19 分钟前
视频转写+LLM分析:课堂录音自动化处理实现
macos·ios·xcode
万粉变现经纪人27 分钟前
如何解决 pip install pillow-simd 报错 需要 AVX2/特定编译器 支持 问题
python·scrapy·beautifulsoup·aigc·pandas·pillow·pip
技术小黑29 分钟前
TensorFlow学习系列08 | 实现猫狗识别
人工智能·python·tensorflow2·vgg-16算法
m0_7505803029 分钟前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
不要秃头的小孩30 分钟前
力扣刷题——77. 组合
数据结构·python·算法·leetcode
AnalogElectronic31 分钟前
markdown文件转docx教程
python