使用Flask获取表单数据 [英] Getting Form data with Flask
问题描述
从Flask中的数据获取数据时,我可以以某种方式将html元素及其值绑定到对象,而无需使用Jinja模板.
When getting from data in Flask, can I somehow bind html elements and their values to an object without using Jinja templating.
还是我必须通过手动HTTP Post发送数据?
Or do I have to send the data via a manual HTTP Post?
推荐答案
我认为您真正要问的是给定客户端JavaScript对象,如何对其进行序列化,以便可以轻松访问数据服务器端".如果这是您的问题,有两种方法可以解决:
I think what you are really asking is "given a client-side JavaScript object, how can I serialize it so that I can easily access the data server-side". If that is your question, there are two ways to do so:
-
您在答案中提供的方式,将对象序列化为JSON并将其作为POST请求的正文提交:
The way you provided in your answer, serializing your object as JSON and submitting it as the body of your POST request:
@app.route("/user", methods=("POST",))
def save_user():
data = request.get_json()
# ... etc. ...
使用 FormData
在客户端:
Using FormData
on the client side:
var yourUser = {
firstname: "Joe",
lastname: "Smith",
email: "joe@smith.com",
password: "12345"
};
var formData = new FormData();
Object.keys(yourUser).forEach(function(key) {
formData.append(key, yourUser[key]);
});
// Post formData back to your controller using XHR
与服务器端正常的 request.form
访问结合:
combined with the normal request.form
access on the server side:
@app.route("/user", methods=("POST",))
def save_user():
data = request.form
# ... etc. ...
这篇关于使用Flask获取表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!