
Ajax request are everywhere in modern web applications. No matter which platform you are using for development, the main scheme is always the same. You send a request to a server side method using JavaScript, jQuery etc. and server processes the request, prepares the response and sends this response to client (browser). Finally, response is received and processed by the client-side code (script) and dynamically generated content is displayed to the users.
Flow is the same in Django. So, what we need to implement here?
1- We need a view function to receive and handle the request
2- We need a mapping in urls.py file to map the request url (which will be specified in the requesting client-side jQuery script) to the view function in 1
3- We need the client-side script to make the request to the url in 2 and handle/render the response
Let me clarify by some simple code snippets.
1- Sample view function:
1 2 3 4 5 6 | def server_function(request, some_id): some_item = Items.objects.get(id=some_id) others = some_item.get_children() result = [(c.id, c.name) for c in others] result = json.dumps(dict(result)) return HttpResponse(result) |
Here we convert the resulting dictionary into a JSON object and return it as an HttpResponse.
2- Sample mapping in urls.py:
1 | url(r'^some/request/url/(\d+)/$', server_function), |
3- Sample jQuery script to send the request and get/render the response:
1 2 3 4 5 6 7 8 9 10 11 12 13 | $(document).ready(function(){ $("#dom_item").click(function(){ $.getJSON("/some/request/url/"+some_value+"/", function(j) { //here j is the JSON formatted response from server-side //render the response here below is just a simple example for printing key and value pairs rendered = ''; Object.keys(j).forEach(function(key, keyIndex) { rendered += key + ' .. ' + j[key]; }); alert(rendered); }); }); }); |
Hope this helps.
Good Luck,
Serdar