Django: Reading Array of JSON objects from QueryDict

前端 未结 2 671
误落风尘
误落风尘 2021-02-05 16:58

How do I pass a composite JSON structure via AJAX call from JS and on the server side, read it as a \"very similar\" data structure in python?

I understand that json for

2条回答
  •  野性不改
    2021-02-05 17:52

    You should stringify your JSON using JSON.stringify(). This will convert the JSON Object into string format so it can be parsed correctly on the other end. On the other end you will need to use json.loads() to "unstringify" the object.

    javascript:

    var test = [{"id": 1},{"id": 2},{"id": 3}];
    $.post(
        "/insert_tc",
        {
          json_data: JSON.stringify(test),
          "type": 'clone',
          "csrfmiddlewaretoken": $csrf_token
        },  
        function(json) {
            //CALLBACK
        },
        "json"
    );  
    

    View:

    import json
    def insert_tc(request):
        if request.method == 'POST':       
            ret = request.POST
            type = ret['type']
            list = json.loads(ret['json_data'])
    

提交回复
热议问题