|
推荐使用 AJAX(异步请求) + Flask路由 实现无刷新提交,步骤如下:
1. HTML页面(关键代码)
- <form id="myForm">
- <input type="text" name="content" id="inputBox">
- <button type="button" onclick="submitForm()">提交</button>
- </form>
- <div id="result"></div>
- <script>
- function submitForm() {
- // 获取输入内容
- let content = document.getElementById('inputBox').value;
-
- // 发送POST请求
- fetch('/submit', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({ content: content })
- })
- .then(response => response.json())
- .then(data => {
- document.getElementById('result').innerHTML = data.message;
- });
- }
- </script>
复制代码
2. Flask后端代码
- from flask import Flask, request, jsonify
- app = Flask(__name__)
- @app.route('/submit', methods=['POST'])
- def handle_submit():
- content = request.json.get('content')
- # 这里添加你的处理逻辑(例如保存到数据库)
- return jsonify({'message': f'成功收到内容:{content}'})
- if __name__ == '__main__':
- app.run(debug=True)
复制代码
优势说明
- 无页面跳转:通过 fetch 发送异步请求
- 数据格式灵活:使用 JSON 格式传输复杂数据
- 实时反馈:通过 .then() 接收服务器响应并更新页面
注意事项
- 如果使用传统表单提交,在路由中改用 request.form.get('字段名')
- 跨域请求需配置 CORS,但本例因前后端同源无需处理
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|