2009-08-09 84 views
4

如何在用户点击链接时在链接下方打开一个div,然后通过AJAX加载内容?Django + Jquery,扩展AJAX div

感谢您的帮助;我无法找到如何。只要在加载页面时静态填充服务器端的div就可以正常工作,但它的内容太多了。

我很寻找特定的Django版本的解决方案,如果任何人有一个?

回答

12

jQuery.load正是这么做的:

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

此获取从/url/to/content/内容,通过#content-id对其过滤和结果注入到div#my-container

编辑:真的没有什么特别的Django,因为它都是客户端。但是,如果你坚持......

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'}), 
) 

您可以下载所有的代码here

1

像这样的事情会工作

<html> 
<head> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
    <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>