views:

578

answers:

2

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?

+1  A: 

Something like this will work

<html>
<head>
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
 <script type="text/javascript">
 function loadDiv() {
  $.get("test.php", function(data){
    $('#thediv').html(data);
  });
 }

</script>
</head>
<body>
<a href="javascript:loadDiv();">Load Div</a>
<div id="thediv"></div>

</body>
</html>
Rob
+7  A: 

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"&gt;&lt;/script&gt;
        {% 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.

piquadrat