【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)
相关推荐
Csvn1 天前
🌟 LangChain 30 天保姆级教程 · Day 13|OutputParser 进阶!让 AI 输出自动转为结构化对象,并支持自动重试!
python·langchain
cch89181 天前
Python主流框架全解析
开发语言·python
sg_knight1 天前
设计模式实战:状态模式(State)
python·ui·设计模式·状态模式·state
好运的阿财1 天前
process 工具与子agent管理机制详解
网络·人工智能·python·程序人生·ai编程
张張4081 天前
(域格)环境搭建和编译
c语言·开发语言·python·ai
weixin_423533991 天前
【Windows11离线安装anaconda、python、vscode】
开发语言·vscode·python
Ricky111zzz1 天前
leetcode学python记录1
python·算法·leetcode·职场和发展
小白学大数据1 天前
Selenium+Python 爬虫:动态加载头条问答爬取
爬虫·python·selenium
用户223586218201 天前
WebKit WebPage API 的引入尝试与自研实现
ios
Hui Baby1 天前
springboot读取配置文件
后端·python·flask