Page switching using AJAX in Django
Asked Answered
E

2

8

I am trying to create site navigation using AJAX. I have navigation menu with links to different views (using {% url name %} in template). The thing I am trying to do is to load the page content using AJAX. The page content I am trying to load is enclosed in content block ({% block content %}).

I also found this snippet http://djangosnippets.org/snippets/942/, but I want to use the views I have already defined and only get the content using ajax.

Any suggestions?

Ebeneser answered 1/7, 2011 at 10:9 Comment(2)
have you solved with django-pjax?Constantia
Basically I did. (with few changes to the original script to allow me to update more than one HTML element in a single request)Leilaleilah
O
7

You should use django-pjax which is built exactly for that kind of thing.

All you will have to do is to, in the base template, include the whole page or just the block content based on whether the request is ajax or not.

django-pjax does the AJAX calls using the jQuery and manipulates history using HTML5 push state API, which is a very good way to do it and also gracefully degrades in IE older versions.

Oster answered 1/7, 2011 at 10:23 Comment(1)
It'd great if it could be used with Django 1.2 too.Oiler
N
3

Template tags like {% block content %} are long gone by the time AJAX sees things. What you want to do is create a named <div> in your content block, like:

{% block content %}
<div id="content"></div>
{% endblock content %}

Then you can use something like this (jQuery) code to load the <div> when needed:

$("#content").load(url, data, loadComplete);

where url is the URL you want to load (HTML expected in return), data is the form data (if any; can be omitted), and loadComplete is the optional function to be called when the data is loaded, and is of the form function loadComplete(responseText, textStatus, XMLHttpRequest) {...}. Even if you don't want to use jQuery, you can get the non-minified jQuery source and see how they do it.

Nodose answered 1/7, 2011 at 10:23 Comment(1)
I know that it is gone, I have a similar div to the one you suggested. The thing I want to do here is to use the already defined view (which would be used without the ajax request) and create some response which will return only the content of the block named content so that I can process it in javascript and replace the content of the div.Leilaleilah

© 2022 - 2024 — McMap. All rights reserved.