[英]Django, update page with ajax
我学习Django,并想使用Ajax。 阅读一些示例,但是有问题。 我需要通过单击带有名称站点的链接来显示所有帖子。 视图:
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);
编写以下内容不是一个好习惯:
<h2><a href="/blog/{{post.id}}"> {{ post.title }} </a> </h2>
看一下{% url %}
模板标记 。
编辑 -免责声明:当前用户没有足够的评论率。 这就是为什么此显然没有答案的答案发布在这里的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.