I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it. This is the piece of js code:
var arr = [1, 2];
$.ajax({
type: 'POST',
url: '/go/',
data: {arr: arr},
success: function (data) {
console.log('Success!');
},
});
And this is from Django view:
def go(request):
if request.method == 'POST':
arr = request.POST['arr']
It gives me KeyError: 'arr'
If I do print(request.POST)
in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>
. Some square brackets appear after 'arr' key. Then if I do arr = request.POST['arr[]']
using the key with square brackets it assings arr
value 2
, so only the last value of the array. Can someone please explain to me why this is happening?
The name of the key is 'arr[]'
, since it contains an array , so you access this with:
def go(request):
if request.method == 'POST':
arr = request.POST.
You need to use .getlist(…)
[Django-doc] to retrieve all values, since the different elements are all passed as individual key-value items.
您正在传递一个列表,因此需要使用 getlist 方法来检索数据。
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.