3

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?

3
  • What kind of output do you want? Commented Oct 13, 2013 at 11:29
  • I'd like to iterate through the array sent with ajax and insert each object from array into database. Commented Oct 13, 2013 at 11:30
  • Can you please show what printing request.GET show? Commented Oct 13, 2013 at 11:33

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This works for me, including PUT method and complex array item
0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.