我有这样的数据结构:
我尝试通过$ .ajax将其发送到服务器:
$.ajax({
type: 'POST',
data: post_obj, //this is my json data
dataType: 'json',
url: '',
success: function(e){
console.log(e);
}
});
我希望通过烧瓶获取服务器:title = request.form['title']
正常工作!
但我如何获得content
?
request.form.getlist('content')
不起作用。
这是firebug中的帖子数据:
非常感谢:D
答案 0 :(得分:17)
您发送的数据编码为查询字符串而不是JSON。 Flask能够处理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']
答案 1 :(得分:2)
如果你检查jQuery提交的POST,你很可能会发现content
实际上是作为content[]
传递的。要从Flask的request
对象访问它,您需要使用request.form.getlist('content[]')
。
如果您希望将其作为content
传递,则可以将traditional: true
添加到$.ajax()
来电。
有关此内容的更多详细信息,请参见http://api.jquery.com/jQuery.ajax/的“数据”和“传统”部分。