Parsing json object sent with Ajax GET method in Django

匿名 (未验证) 提交于 2019-12-03 08:56:10

问题:

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?

回答1:

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



回答2:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!