2015-01-11 123 views
0

我想從jQuery發送一些數據到Tornado Python後端。Jquery POST JSON數據到Python後端

下面是簡單的例子:

$.ajax({ 
    url: '/submit_net', 
    dataType: 'json', 
    data: JSON.stringify({"test_1":"1","test_2":"2"}), 
    type: 'POST', 
    success: function(response) { 
     console.log(response); 
    }, 
    error: function(error) { 
     console.log(error); 
    } 

}); 

這裏是Python代碼:

class submit_net(tornado.web.RequestHandler): 
    def post(self): 
     data_json = self.request.arguments 
     print data_json 

當我點擊提交按鈕,然後Python的後臺檢索以下字典

{'{"test_1":"1","test_2":"2"}': ['']} 

但我想檢索完全相同的d作爲jQuery發送的字典:

{"test_1":"1","test_2":"2"} 

你能幫助我我做錯了什麼嗎?

+1

您是否嘗試過沒有扎線? – Jai

+0

@Jai:不,那麼他們不會發送JSON。這是*接收端要解決的問題*。 –

回答

3

request.arguments只應用於表格編碼數據。使用request.body訪問JSON的原始數據和解碼與json module

import json 

data_json = self.request.body 
data = json.loads(data_json) 

request.body包含字節,這是在Python 2罰款,但如果你使用Python 3,你需要先解碼那些爲Unicode。獲得請求的字符集與cgi.parse_header()

from cgi import parse_header 

content_type = self.request.headers.get('content-type', '') 
content_type, params = parse_header(content_type) 
charset = params.get('charset', 'UTF8') 
data = json.loads(data_json.decode(charset)) 

此默認爲UTF-8字符集,它作爲一個缺省值是僅適用於JSON請求;其他請求內容類型需要以不同的方式處理。

你可能想明確表示要發送一個JSON體通過設置內容類型:

$.ajax({ 
    url: '/submit_net', 
    contentType: "application/json; charset=utf-8", 
    data: JSON.stringify({"test_1":"1","test_2":"2"}), 
    type: 'POST', 
    success: function(response) { 
     console.log(response); 
    }, 
    error: function(error) { 
     console.log(error); 
    } 
}); 

,並試圖解碼之前在龍捲風POST處理程序驗證正在使用的內容類型POST爲JSON:

content_type = self.request.headers.get('content-type', '') 
content_type, params = parse_header(content_type) 
if content_type.lower() != 'application/json': 
    # return a 406 error; not the right content type 
    # ... 

charset = params.get('charset', 'UTF8') 
data = json.loads(data_json.decode(charset)) 

當你用Python回到JSON回的jQuery時,才需要$.ajaxdataType參數;它告訴jQuery爲您解碼響應。即使如此,這並不是嚴格需要的,因爲application/json響應Content-Type標頭就足夠了。

+0

你會在龍捲風中使用什麼樣的處理程序? –