Jquery POST JSON data to Python backend



我想将一些数据从jQuery发送到Tornado 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"}': ['']}

但我想检索与 jQuery 发送的完全相同的字典:

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

你能帮我做错什么吗?

request.arguments只能用于表单编码数据。使用 request.body 访问 JSON 原始数据并使用 json 模块进行解码:

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 解码为 JSON 之前,在 Tornado POST 处理程序中验证是否正在使用该内容类型:

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))

只有当你将JSON从Python返回回jQuery时,才需要$.ajax dataType参数;它告诉jQuery为你解码响应。即使这样,这也不是严格需要的,因为application/json响应 Content-Type 标头就足够了。

最新更新