2013-04-04 76 views
5

我想將包含來自客戶端的嵌套對象的json對象傳遞給我的服務器。如何使用jquery ajax正確地將json對象傳遞給flask服務器

在客戶端

,我的數據結構是這樣的:

var response = {}; 
response['screening'] = '1'; 
response['assistance'] = 'wheelchair access'; 
response['guests'] = {}; 
response['guests']['1'] = {} 
response['guests']['1']['first'] = 'John' 
response['guests']['1']['last'] = 'Smith' 
response['guests']['2'] = {} 
response['guests']['2']['first'] = 'Dave' 
response['guests']['2']['last'] = 'Smith' 

和我的Ajax調用是這樣的:

$.ajax({ 
    type: "POST", 
    url: window.location.pathname, 
    data: response 
}).done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

此數據發佈到我的服務器,這是使用後運行蟒蛇燒瓶,我使用request.form對象來檢查從客戶端發佈的內容。我想對數據進行結構化以同樣的方式,但是,這是在服務器上的輸出:

ImmutableMultiDict([('guests[1][first]', u'John'), ('screening', u'2'), ('guests[2][last]', u'Smith'), ('guests[2][first]', u'Dave'), ('assistance', u'wheelchair access'), ('guests[1][last]', u'Smith')]) 

,你可以看到,響應[「客人」]對象得到平滑,並將其所有孩子,如:

'客人[2] [首頁]'

...只是一個字符串,而不是他們的父母響應[ '客人']的元素。

有沒有更好的方法將這個數據塊從我的客戶端發送到我的服務器,並正確地維護其結構?

謝謝!

回答

11

你可以把你的對象作爲JSON字符串:

var data = { 
    screening: '1', 
    assistance: 'wheelchair access', 
    guests: [ 
     { 
      first: 'John', 
      last: 'Smith' 
     }, 
     { 
      first: 'Dave', 
      last: 'Smith' 
     } 
    ] 
}; 

$.ajax({ 
    type: 'POST', 
    url: window.location.href, 
    data: JSON.stringify(response), 
    dataType: 'json', 
    contentType: 'application/json; charset=utf-8' 
}).done(function(msg) { 
    alert("Data Saved: " + msg); 
}); 

然後用request.json來訪問它。

+0

完全有效!謝謝。有一件事是.done()方法永遠不會執行,即使我可以在服務器上看到數據,並且當我檢查chrome dev網絡選項卡時,此請求也有POST 200 OK。 – SeanPlusPlus 2013-04-04 04:33:00

+0

不要在意上面的評論。我需要從服務器中聲明我的響應。再次感謝您的幫助。 – SeanPlusPlus 2013-04-04 04:39:32

0

在客戶端,您需要將該javascript對象轉換爲json字符串。要做到這一點,您可以使用此:

JSON.stringify(my_object) // This will return a string that you can pass in you ajax request 

然後在服務器端,您需要使用JSON模塊對象轉換爲蟒蛇dictionnary:

import simplejson 
my_new_object = simplejson.loads(my_json) // my_json is my_object from the client (previously called my_object) 

my_new_object現在是一個Python dictionnary ,你可以隨心所欲地做任何事

相關問題