2015-01-11 120 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

你会在龙卷风中使用什么样的处理程序? –