Django,使用Ajax更新页面
我在学习Django,想用ajax。看了一些例子,但遇到问题。 我需要通过点击一个名为“site”的链接来显示所有的帖子。 视图:
def archive(request, page_number=1):
posts = BlogPost.objects.all()
current_page = Paginator(posts, 3)
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
else:
t = loader.get_template("archive.html")
c = Context({'posts': current_page.page(page_number),
'username': auth.get_user(request).username})
return HttpResponse(t.render(c))
base.html:
<h1><a class="refresh" >mysite.example.com</a></h1> (I need click it and update posts )
<div class="content">
<div>
{% block content %}
{% endblock %}
</div>
</div>
archive.html:
{% extends "base.html" %}
{% block content %}
{% for post in posts %}
{% include "archive_ajax.html" %}
{% endfor %}
{% endblock %}
archive_ajax.html(问题不在这里,我是说我首先需要解决上面的问题):
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
<p> author: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
在base.html中引入了jquery:<script src="/static/jquery-1.11.1.min.js" type="application/javascript"></script>
然后我尝试写代码:
$(document).ready(function(){
$(".refresh").click(function(){
console.log('clicked');
$(".content").load("/blog/");
});
});
当我点击链接时,我在应该显示帖子的地方看到了内容:
{"content": "
\n
\u0430\u0432\u0442\u043e\u0440:
\n
\n
\n", "status": 200, "statusText": "OK"}
在命令行中,我看到"GET /blog/ HTTP/1.1" 200 151
我尝试了另一种方法,写了:
$(document).ready(function(){
$(".refresh").click(function(){
$.ajax({
type: "GET",
url: "/blog/",
success : function(newdata) {
$('.content').html(newdata);
}
});
});
});
现在我在应该显示帖子的地方什么也看不到。 在命令行中,我看到"GET /blog/ HTTP/1.1" 200 151
在视图中我添加了打印语句:
if request.is_ajax():
t = loader.get_template("archive_ajax.html")
print('it is query'`)
在命令行中我看到消息——这是ajax和js的查询。
我使用的是python 2.7.3,Django 1.6.5和jquery 1.11.1.min。
谢谢大家!我找到了我的错误,问题出在ajax和模板archive_ajax.html上。我觉得是我的不小心。在模板中我忘记为{{posts}}添加循环。现在是:
{% for post in posts %}
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
<p>автор: {{ post.author.username }}</p>
<p> {{ post.timestamp | date:"l, F jS, Y" }} </p>
<p> {{ post.body }} </p>
{% endfor %}
在ajax中我也修正了:
$('.content').html(newdata.content);
相关问题:
1 个回答
1
这样写代码并不好:
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
可以看看 {% url %} 这个 模板标签。
补充说明 - 说明一下:当前用户的权限不够,不能评论。所以这看起来没有回答的回答就放在这里了。