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
format
variable - Does format is
json
mean that data given to function is json or data which will be recived is json - Can anyone give me simple exam开发者_运维百科ple 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
- From where the function is getting format variable
In practice, there are lots of ways this format could be populated. HTTP provides an Accept:
header that requests can use to indicate the preferred Content-Type
for the response. On the client, you might use xhr.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:
urlpatterns = patterns('',
# ...
(r'^xhr_test.(?<format>.*)$', 'path.to.xhr_test'),
)
2 . Does format is json mean that data given to function is json or data which will be recived is json
This particular view doesn't do anything at all with the request body, and is certainly providing a response body in the supplied format
4 . How will I use that data when i get that response in jquery function
Depending 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 use jQuery.parseJSON
to process the json data, and that will return the same JavaScript objects.
- From the urlconf, just like it says in the article right below it.
- The query set will be serialized as JSON.
- It will be the query set represented as either XML or JSON.
python manage.py shell
is your friend. - You will decode it, then iterate over it.
- You'll need to find some other format to serialize it in instead.
精彩评论