简体   繁体   中英

Sending an array from javascript to Django

I have an array of objects in javascript. Arr = [0: {k;v}, 1: {k,v}] etc etc... with a lot of fields in them.

I'm having trouble sending them to Django.

I've tried doing JSON.stringify and sending it to django and retrieving with both getlist and get .

The problem is I get a list with two dictionaries inside but I cannot figure out how to iterate through the list.

Current code is sending the array to Django this way:

{'data[]': JSON.stringify(arr)}

And in Django:

req = request.POST.getlist('data[]', None)

What I get back when I print the statement is:

[ { dict of key, value pairs }, { dict of key value pairs }]

I cannot figure out how to iterate through the list of dictionaries and retrieve the key value pairs and keep them as separate.

Solved with help from the comments.

Instead of using .getlist I used .get and wrapped it in json.loads().

From there I was able to look through this way:

req = json.loads( request.POST.get('data[]', None) )

for each_row in req:
    for k, v in each_row.items():
        print(k, v)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM