简体   繁体   English

从javascript发送数组到Django

[英]Sending an array from javascript to Django

I have an array of objects in javascript. 我在javascript中有一组对象。 Arr = [0: {k;v}, 1: {k,v}] etc etc... with a lot of fields in them. Arr = [0: {k;v}, 1: {k,v}]等,其中有很多字段。

I'm having trouble sending them to Django. 我在将它们发送到Django时遇到问题。

I've tried doing JSON.stringify and sending it to django and retrieving with both getlist and get . 我尝试做JSON.stringify并将其发送到django并使用getlistget检索。

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: 当前代码以这种方式将数组发送给Django:

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

And in Django: 在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(). 我没有使用.getlist而是使用.get并将其包装在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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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