如何将类似JSON的数据结构发送给Flask?
我有一个这样的数据结构:
我想通过 $.ajax 把它发送到服务器:
$.ajax({
type: 'POST',
data: post_obj, //this is my json data
dataType: 'json',
url: '',
success: function(e){
console.log(e);
}
});
然后我想在服务器上用 flask 获取它:title = request.form['title']
这个方法很好用!
但是我该怎么获取 content
呢?
request.form.getlist('content')
这个方法不管用。
这是在 firebug 中看到的发送数据:
非常感谢 :D
2 个回答
2
如果你查看通过 jQuery 提交的 POST 请求,你会发现 content
实际上是以 content[]
的形式传递的。要从 Flask 的 request
对象中获取这个数据,你需要使用 request.form.getlist('content[]')
。
如果你希望它以 content
的形式传递,你可以在你的 $.ajax()
调用中添加 traditional: true
。
关于这个内容的更多细节,可以在 http://api.jquery.com/jQuery.ajax/ 的 'data' 和 'traditional' 部分找到。
17
你现在发送的数据是用查询字符串的方式编码的,而不是用JSON格式。Flask可以处理JSON格式的数据,所以用JSON发送数据会更合适。你需要在客户端做以下操作:
$.ajax({
type: 'POST',
// Provide correct Content-Type, so that Flask will know how to process it.
contentType: 'application/json',
// Encode your data as JSON.
data: JSON.stringify(post_obj),
// This is the type of data you're expecting back from the server.
dataType: 'json',
url: '/some/url',
success: function (e) {
console.log(e);
}
});
在服务器端,你可以通过 request.json
来访问数据(这个数据已经被解码了):
content = request.json['content']