亮点包括:fetch 核心原理剖析、登录重定向的异步处理、利用响应状态码动态更新ui、以及如何处理json/文本等不同格式的返回数据。
你将学到:
- fetch api 的“承诺”机制与基础用法
- 如何用 flask 构建 restful 风格的 api 端点
- 登录表单提交:告别传统表单刷新,实现平滑跳转
- 数据操作:前端一个请求,后端处理,前端ui即时响应
- 根据后端返回的不同数据类型(json/text)进行精准处理
1. 初识fetch:现代web的通信信使
fetch() 是浏览器提供的、基于 promise 的现代网络请求api。它取代了古老的 xmlhttprequest,让异步数据请求变得清晰、简洁。你可以把它想象成一个专业的“信使”。
它的基本工作流程是:你给信使(fetch)一个地址(url)和指示(配置对象),它立刻返回一个“承诺收据”(promise)。这个承诺最终会兑现为“响应包裹”(response对象),你需要打开这个包裹(调用如.json(), .text()等方法)才能拿到里面的真实数据。
// 一个最简单的get请求示例
fetch('/api/data')
.then(response => response.json()) // 打开包裹,解析json数据
.then(data => console.log(data)) // 处理真实数据
.catch(error => console.error('出错啦:', error)); // 处理错误2. 实战准备:flask后端的简单配置
为了让前端fetch能顺利与后端“对话”,我们需要一个能处理json、并能进行跨域资源共享(cors)的flask应用。首先,安装必要库:
pip install flask flask-cors
接着,搭建一个基础的后端服务:
from flask import flask, request, jsonify
from flask_cors import cors
app = flask(__name__)
cors(app) # 允许前端跨域请求,开发时非常方便
# 我们将在后续场景中逐步填充这个app的路由
if __name__ == '__main__':
app.run(debug=true)3. 场景一:登录表单提交与页面重定向
传统表单提交会刷新页面,体验割裂。使用fetch,我们可以实现无刷新登录,并根据后端指令进行前端路由跳转。
前端 (javascript):拦截表单提交事件,使用fetch发送数据。
document.getelementbyid('loginform').addeventlistener('submit', function(event) {
event.preventdefault(); // 阻止表单默认提交行为
const formdata = new formdata(this);
// 或者将数据转换为json: json.stringify(object.fromentries(formdata))
fetch('/api/login', {
method: 'post',
body: formdata, // 发送formdata对象
// headers: { 'content-type': 'application/json' }, // 如果发送json需设置此header
})
.then(response => response.json()) // 解析后端返回的json
.then(result => {
if (result.success) {
// 登录成功,使用前端路由跳转,而非后端重定向
window.location.href = result.redirect_url || '/dashboard';
} else {
// 登录失败,动态更新页面上的错误提示元素
document.getelementbyid('error-msg').textcontent = result.message;
}
})
.catch(error => console.error('error:', error));
});后端 (flask):验证数据,返回包含状态和指令的json,而不是直接返回重定向的html。
@app.route('/api/login', methods=['post'])
def login():
username = request.form.get('username')
password = request.form.get('password')
# 这里应是你的验证逻辑,例如查询数据库
if username == 'admin' and password == 'secret':
# 返回成功状态和前端跳转地址
return jsonify({'success': true, 'redirect_url': '/dashboard'})
else:
# 返回失败状态和错误信息
return jsonify({'success': false, 'message': '用户名或密码错误'}), 4014. 场景二:动态新增与修改数据
在管理系统中,新增或修改一条数据后,我们希望列表能立即更新,而无需刷新整个页面。
核心思路:fetch请求成功后,在.then()中根据后端返回的最新数据,直接操作dom更新ui。
// 假设有一个保存按钮,用于提交新增或修改的数据
savebutton.addeventlistener('click', () => {
const itemdata = { title: '新项目', status: 'active' };
fetch('/api/items', {
method: 'post', // 新增用post,修改可能是put或patch
headers: { 'content-type': 'application/json' },
body: json.stringify(itemdata)
})
.then(response => response.json())
.then(newitem => {
// 关键步骤:请求成功后,动态更新前端列表
const itemlist = document.getelementbyid('itemlist');
const newitemelement = document.createelement('li');
newitemelement.id = `item-${newitem.id}`;
newitemelement.innerhtml = `${newitem.title} ${newitem.status}`;
itemlist.appendchild(newitemelement);
// 或者,如果是修改操作,可以找到对应的dom元素更新其内容
// const olditemelement = document.getelementbyid(`item-${newitem.id}`);
// olditemelement.innerhtml = ...;
alert('操作成功!'); // 或更优雅的提示
});
});对应的flask后端需要返回创建或更新后的完整数据对象,以便前端使用。
5. 场景三:处理不同类型的响应数据
后端可能返回json,也可能返回纯文本或html片段。fetch的response对象提供了不同的方法来处理。
处理json (最常用):如上文所示,使用response.json()。
处理文本:例如后端返回一个简单的成功消息或csv数据。
fetch('/api/export')
.then(response => response.text())
.then(textdata => {
console.log(textdata);
// 处理文本数据...
});检查响应状态:在解析数据前,先检查请求是否真正成功是个好习惯。
fetch('/api/some-data')
.then(response => {
if (!response.ok) { // 检查http状态码是否在200-299之间
throw new error(`http error! status: ${response.status}`);
}
return response.json(); // 状态正常才解析json
})
.then(data => /* 处理数据 */)
.catch(error => /* 处理网络错误或状态码错误 */);6. 完整代码参考与总结
下面是一个整合了登录和新增项目的超简易完整示例:
# app.py (flask后端)
from flask import flask, request, jsonify
from flask_cors import cors
app = flask(__name__)
cors(app)
items = [] # 用一个简易列表模拟数据库
@app.route('/api/login', methods=['post'])
def login():
data = request.get_json()
if data.get('user') == 'demo':
return jsonify({'success': true, 'token': 'fake-jwt-token'})
return jsonify({'success': false}), 401
@app.route('/api/items', methods=['get', 'post'])
def handle_items():
if request.method == 'get':
return jsonify(items)
else: # post
new_item = request.get_json()
new_item['id'] = len(items) + 1
items.append(new_item)
return jsonify(new_item), 201
if __name__ == '__main__':
app.run(debug=true)<!-- index.html (部分前端) -->
<script>
// 登录
fetch('/api/login', {
method: 'post',
headers: {'content-type': 'application/json'},
body: json.stringify({user: 'demo', pass: 'demo'})
}).then(r => r.json()).then(console.log);
// 新增项目并更新列表
fetch('/api/items', {
method: 'post',
headers: {'content-type': 'application/json'},
body: json.stringify({name: 'new task'})
})
.then(r => r.json())
.then(newitem => {
const list = document.getelementbyid('list');
list.innerhtml += `<li>${newitem.id}: ${newitem.name}</li>`;
});
</script>总结一下:fetch + flask 的组合,通过“请求-响应-json”的模式,将前后端解耦,让web交互变得更加动态和高效。
关键在于:前端负责交互和ui更新,后端负责数据和逻辑,两者通过清晰的api契约进行通信。
到此这篇关于python flask结合前端fetch搞定表单提交和页面刷新的文章就介绍到这了,更多相关python flask fetch表单提交内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论