Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an array in Django posted via Ajax

When I try to send an array to Django via Ajax (jQuery)

JavaScript code:

new_data = ['a','b','c','d','e']; $.get('/pythonPage/', {'data': new_data},function(data){}); 

and I try to read the array:

Python:

request.GET.get("data[]") 

I get only the last array value:

'e' 

What am I doing wrong?

like image 234
Erez Avatar asked Aug 24 '12 00:08

Erez


People also ask

How send data from Ajax to Django?

To send and receive data to and from a web server, AJAX uses the following steps: Create an XMLHttpRequest object. Use the XMLHttpRequest object to exchange data asynchronously between the client and the server. Use JavaScript and the DOM to process the data.

What is request method == post in Django?

method == "POST" is a boolean value - True if the current request from a user was performed using the HTTP "POST" method, of False otherwise (usually that means HTTP "GET", but there are also other methods).


Video Answer


2 Answers

You're looking for the QueryDict's getlist

request.GET.getlist('data') request.GET.getlist('data[]') request.GET.getlist('etc') 

https://docs.djangoproject.com/en/2.0/ref/request-response/#django.http.QueryDict.getlist

like image 146
Yuji 'Tomita' Tomita Avatar answered Sep 17 '22 18:09

Yuji 'Tomita' Tomita


Quite old question but let me show you full working code for this. (Good for newbie :)

In your template

data = {     'pk' : [1,3,5,10] }  $.post("{% url 'yourUrlName' %}", data,      function(response){         if (response.status == 'ok') {             // It's all good             console.log(response)         } else {             // Do something with errors         }     }) 

urls.py

urlpatterns = [     url(r'^yourUrlName/', views.yourUrlName, name='yourUrlName'), #Ajax ] 

views.py

from django.views.decorators.http import require_POST from django.http import JsonResponse   @require_POST def yourUrlName(request):     array = request.POST.getlist('pk[]')      return JsonResponse({             'status':'ok',             'array': array,         }) 
like image 32
Michael Stachura Avatar answered Sep 18 '22 18:09

Michael Stachura