2013-02-26 31 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