2013-02-26 64 views
13

我有一个数据结构是这样的:如何发布数据结构像JSON到烧瓶?

enter image description here

我尝试$就发给服务器:

$.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')不起作用。

这是萤火后数据:

enter image description here

非常感谢:d

+0

怎么样'内容=的Request.Form [“内容” ]'? :) – favoretti 2013-02-26 03:11:47

+0

@favoretti无法工作:'BadValueException:类型为“content”的字段的值不正确。原因:“值不是(got:list)的实例”' – Robin 2013-02-26 03:19:00

+0

好吧,request.form.getlist('content')'返回什么?关于“不行”的一些更具体的细节可能会有所帮助。不幸的是,这里没有方便的测试瓶来测试。 – favoretti 2013-02-26 03:25:36

回答

16

您正在将您的数据编码为查询字符串而不是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'] 
+0

太棒了!谢谢 :) – Robin 2013-02-26 14:37:25

2

如果检查POST提交的jQuery,你很可能会看到content实际上是通过为content[]。要从Flask的request对象访问它,则需要使用request.form.getlist('content[]')

如果您希望将其作为content传递,您可以将traditional: true添加到您的$.ajax()调用中。

关于这个的更多细节可以在http://api.jquery.com/jQuery.ajax/的'data'和'traditional'部分找到。

+0

谢谢你的回答。 – Robin 2013-02-26 04:00:05

+0

当我将'traditional:true'设置为$ .ajax时。我在服务器上收到了一个类似[[object Object]]的字符串......但这不是我想要的: – Robin 2013-02-26 04:04:43

+0

不同的服务器端技术处理的方式不同,你可能想看看Audrius提供的关于JSON的答案 – dirn 2013-02-26 12:29:46