Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django + Jquery, expanding AJAX div

How can I, when a user clicks a link, open a div right underneath the link which loads it's content via AJAX?

Thanks for the help; I cannot find out how to. Just statically filling the div on the server side while loading the page works fine, but it's too much content for that.

I'm kind of looking for a specific Django version of the solution if anyone has one?

like image 374
CharlesS Avatar asked Aug 09 '09 20:08

CharlesS


1 Answers

jQuery.load does exactly that:

$("div#my-container").load("/url/to/content/ #content-id")

this fetches the content from /url/to/content/, filters it by #content-id and injects the result into div#my-container.

edit: there's really nothing Django-specific about this, since it's all client-side. But if you insist...

templates/base.html

<html>
    <head>
        <title>My funky example</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        {% block extrahead %}{% endblock %}
    </head>
    <body>
        {% block content %}{% endblock %}
    </body>
</html>

templates/page.html

{% extends "base.html" %}
{% block extrahead %}
    <script type="text/javascript">
        $(function(){
            $('a.extendable').click(function(){
                $(this).after($('<div class="external-content"></div>').load($(this).attr('href') + ' #content'));
                return false;
            });
        });
    </script>
{% endblock extrahead %}
{% block content %}
    <p>Hi! <a href="/external/content/a/" class="extendable">Click here</a> and wait for something funny to happen!</p>
    <p><a href="/external/content/b/" class="extendable">This link</a> is cool, too!</p>
{% endblock content %}

templates/a.html

{% extends "base.html" %}
{% block content %}
    <div id="content">so long and thanks for all the fish</div>
{% endblock %}

templates/b.html

{% extends "base.html" %}
{% block content %}
    <div id="content">Don't panic</div>
{% endblock %}

urls.py

from django.conf.urls.defaults import *
urlpatterns = patterns('django.views.generic.simple',
    (r'^$',                    'direct_to_template', {'template': 'page.html'}),
    (r'^external/content/a/$', 'direct_to_template', {'template': 'a.html'}),
    (r'^external/content/b/$', 'direct_to_template', {'template': 'b.html'}),
)

You can download all the code here.

like image 146
Benjamin Wohlwend Avatar answered Sep 26 '22 01:09

Benjamin Wohlwend