I read about JSON from internet but still i have not got the grasp of it. I am reading this article
http://webcloud.se/log/AJAX-in-Django-with-jQuery/
I could not understood the first part where the function is using JSON
def xhr_test(request, format):
if request.is_ajax():
if format == 'xml':
mimetype = 'application/xml'
if format == 'json':
mimetype = 'application/javascript'
data = serializers.serialize(format, ExampleModel.objects.all())
return HttpResponse(data,mimetype)
# If you want to prevent non XHR calls
else:
return HttpResponse(status=400)
My Main Problems are
- From where the function is getting
formatvariable - Does format is
jsonmean that data given to function is json or data which will be recived is json - Can anyone give me simple example that what will be the ouput of this function
data = serializers.serialize(format, ExampleModel.objects.all()) - How will I use that data when i get that response in jquery function
- If i don’t use JSON in above function then how will the input and response back will chnage
Thanks
In practice, there are lots of ways this format could be populated. HTTP provides an
Accept:header that requests can use to indicate the preferredContent-Typefor the response. On the client, you might usexhr.setRequestHeader('accept', 'application/json')to tell the server that you want your response in json format. In practice, though, very few frameworks actually do this. This being django, arguments to view functions are usually set in the urlconf, you might craft a urlconf like this:This particular view doesn’t do anything at all with the request body, and is certainly providing a response body in the supplied
formatDepending on how complicated your request needs to be, you can use
jQuery.getJSON, which will pass your callback with regular JavaScript objects that result from parsing the JSON. If you need to do a bit more work to get the request right, you can usejQuery.parseJSONto process the json data, and that will return the same JavaScript objects.