views.py:
def get_accounts( request ):
if request.is_ajax():
res = ["foo","bar"]
json = simplejson.dumps(res)
return HttpResponse(json, mimetype='application/json')
return HttpResponseNotFound
urls.py:
( r'^get_accounts/$', 'get_accounts'),
client.html:
$.get('/django/backoffice/bopanel/get_accounts',{'acc':$('.nr').text().replace(/^\s+||\s+$/g,'')}, function(data) {
alert(data[0]);
});
I was very surprised getting an alert box with content:
"["
What means I got string instead of array, which i very strange for me and definitely not something what i expected.
In firebug i see two subsequent GET requests:
GET http://127.0.0.1:8000/django/backoffice/bopanel/...nts?acc=17114%2FF01055%2FTP%0A%09%09++++++++++++
301 MOVED PERMANENTLY
24ms
GET http://127.0.0.1:8000/django/backoffice/bopanel/...ts/?acc=17114%2FF01055%2FTP%0A%09%09++++++++++++
200 OK
16ms
I don’t understand why I get two requests and why the first have 301 status. I don’t understand how this makes json appear as string. Any help?
Django by default appends a slash to any URL without one (see common middleware).
You want to use
content_typeinstead ofmimetype, ie: