Reputation: 6041
I have created an Ajax request which should be processed by Django:
var tracks = [{'artist':'xxx', 'track':'yyy', 'duration':100},
{'artist':'xxx', 'track':'yyy', 'duration':100},
{'artist':'xxx', 'track':'yyy', 'duration':100}];
$.ajax({
type: 'GET',
url: ROOT_URL + '/snv/',
data: {tracks: tracks},
dataType: 'json'
}).done(function (data) {
// do something
}).fail(function (data) {
// do something else
});
and I have a Python function to retrieve that data:
def snv(request):
for track in request.GET:
print track
But this function prints something like:
tracks[1][artist]
tracks[0][track]
tracks[0][duration]
tracks[2][artist]
tracks[1][track]
tracks[1][duration]
tracks[2][duration]
tracks[0][artist]
tracks[2][track]
If I print request.GET
I get this:
<QueryDict: {u'tracks[1][artist]': [u'Artist 02'], u'tracks[0][track]': [u'title 00'], u'tracks[0][duration]': [u'202'], u'tracks[2][artist]': [u'Artist 04'], u'tracks[1][track]': [u'title 02'], u'tracks[1][duration]': [u'506'], u'tracks[2][duration]': [u'233'], u'tracks[0][artist]': [u'Artist 00'], u'tracks[2][track]': [u'title 04']}>
How to process my object properly?
Upvotes: 3
Views: 4905
Reputation: 15519
You can solve it by using json encoding:
encode in javascript
data: {tracks: JSON.stringify(tracks)}
decode in the view
tracks = json.loads(request.POST.get('tracks'))
This way you avoid 3rd party parser :)
Upvotes: 5
Reputation: 6041
Ok, I solved it like this:
changed my Ajax request from GET to POST,
followed this to acquire CSRF_token,
used this parser to parse my object,
and finally changed my Python function:
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def startNewVoting(request):
from querystring_parser import parser
p = parser.parse(request.POST.urlencode())
for key, track in p['tracks'].iteritems():
print track
# save to db...
Upvotes: 0