Blog Entry 12 years, 5 months ago

Tiny notice for JSON + Ajax + Django

You should be careful with the returned value or there will be no success function called. Let make an example of the view code on Django side, which processed the Ajax request and return results if necessary. ... return HttpResponse("{'code':'1'}", mimetype='application/json')

Let make an example of the view code on Django side, which processed the Ajax request and return results if necessary.

...
return HttpResponse("{'code':'1'}", mimetype='application/json')

Okay, that is what will (successfully) be returned to the calling page; but no registered JavaScript function will be executed. The problem stays on the JSON string and mimetype transfered to response. 

When the Json string is defined by using single-quote for string encapsulation, that will not be identified as application/json at client side. That is somehow not very flexible, I think. Therefore, the better return command is:

return HttpResponse('{"code":"1"}', mimetype='application/json')

But really, we should use django.utils.simplejson instead:

from django.utils import simplejson
...

response_dict = {}
response_dict['code'] = '1'
return
HttpResponse(simplejson.dumps(response_dict),
                    mimetype
='application/json')
Recent Reads