python3.x - How to parse python django when passing json to the backend through ajax
过去多啦不再A梦
过去多啦不再A梦 2017-06-12 09:23:52
0
2
907

My json content is like this:

{
    "type":"user",
    "ifor":[
        {
            "id":001,
            "name:"lison"
        },
        {
            "id":002,
            "name":"wei"
        }
    ]
}

In JS, I use the ajax method of jquery to pass it, and write it like this:

$.ajax("url",{
    type:"post",
    data:{
        type:"user",
        ifor: [
            {
                id:001,
                name:"lison"
            },
            {
                id:002,
                name:"wei"
            }
        ]
    },
    success:function(){}
})

Mine is python3.6, and django is 1.11.1. How should I receive it in views.py in django? I checked a lot online, some said json.loads(request.body), some said simplejson.loads(request.raw_post_data), but they all seemed to have problems. Could you please tell me how to receive and parse it

过去多啦不再A梦
过去多啦不再A梦

reply all(2)
女神的闺蜜爱上我

Front-end ajax:

data = {};
$.ajax({
    type: "post",
    url: "url",
    dataType: "json",
    data: JSON.stringify(data),
    success: function(result) {
    }
});

Backend value:

import json
data = json.loads(request.body)
print data['key']
代言

You must first determine what the content you pass to the backend looks like. It cannot be directly json.loads
Assume that the source code of the view corresponding method is as follows

def test(req):
    print(req.POST)   # 通过输出看看前端传过来的数据是什么
    return HttpResponse('test')

Only the json format that conforms to '{"aa":"xxx"...}' can be recognized and deserialized by json.loads. If the result returned is not like this json Format, then you need to adjust the front-end ajax to be able to construct such data. Specifically, you can construct it through dataType: json or through string splicing. For details, you can Google it yourself: ajax passes json data

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template