Flask机器学习应用:如何将jsonify结果返回至training.html页面
解决Flask返回JSON后无法在原页面展示结果的问题
核心问题
你当前的问题根源是表单提交触发了页面跳转,Flask返回的JSON被浏览器直接渲染成新的空白页面,而非留在training.html中由JavaScript接收并处理。必须改用异步AJAX请求提交数据,才能实现页面不刷新的同时,接收并展示预处理结果。
具体修改步骤
1. 调整HTML表单,阻止默认跳转行为
给表单添加阻止默认提交的逻辑,避免页面跳转:
<form id="preprocessForm" onsubmit="return false;"> <!-- 你的表单输入元素 --> <button type="button" onclick="submitPreprocessData()">提交预处理</button> </form> <!-- 初始隐藏的结果表格 --> <table id="resultTable" style="display: none;"> <thead> <tr> <th>特征1</th> <th>特征2</th> <!-- 根据你的数据结构定义表头 --> </tr> </thead> <tbody id="tableBody"></tbody> </table>
2. 重写JavaScript,用AJAX异步提交数据
使用fetch API发送请求,接收Flask返回的JSON后,动态填充表格并显示:
function submitPreprocessData() { // 收集表单数据 const form = document.getElementById('preprocessForm'); const formData = new FormData(form); // 发送异步POST请求 fetch('/your-preprocess-route', { method: 'POST', body: formData }) .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then(processedData => { // 填充结果表格 populateResultTable(processedData); // 显示隐藏的表格 document.getElementById('resultTable').style.display = 'table'; }) .catch(error => { console.error('处理出错:', error); alert('数据预处理失败,请检查控制台信息'); }); } function populateResultTable(data) { const tbody = document.getElementById('tableBody'); tbody.innerHTML = ''; // 清空旧数据 // 遍历预处理后的数据,生成表格行 data.forEach(item => { const row = document.createElement('tr'); // 根据你的数据结构生成单元格,示例如下 row.innerHTML = ` <td>${item.feature1}</td> <td>${item.feature2}</td> `; tbody.appendChild(row); }); }
3. 确认Flask路由的JSON返回逻辑
你的现有路由逻辑无需大幅修改,只要确保用jsonify返回结构正确的JSON即可:
from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/your-preprocess-route', methods=['POST']) def preprocess_data(): # 获取表单提交的数据 input_data = request.form # 执行你的数据预处理逻辑 processed_result = your_preprocessing_function(input_data) # 返回JSON格式的结果 return jsonify(processed_result) if __name__ == '__main__': app.run(debug=True)
关键注意事项
- 避免使用
<button type="submit">,改用type="button"或通过JS阻止默认提交行为,防止页面跳转。 - 调试时打开浏览器控制台(F12),查看网络请求状态和返回的JSON结构是否符合预期。
- 如果前端与后端不同源,需安装并配置
flask-cors扩展解决跨域问题。
内容的提问来源于stack exchange,提问作者M Ali Akbar Sinaga
相关产品推荐
相关产品推荐

