Django 使用 AJAX 加载更多注释



在个人资料页面中,我想显示用户的帖子。每个帖子可能有几个评论,我不想显示帖子的所有评论,而是只想显示几条评论并添加加载更多评论选项。如果用户单击加载更多评论,那么我想显示更多评论。有什么更好的方法呢?我已经使用无限滚动使用分页进行帖子。我认为这可能不适用于评论。

我的当前代码如下所示

{% for post in post_queryset %}
<div class="title">
{{ post.title }}
</div>
{% for comment in post.comments.all %}
</div>
{{ comment.text }}
</div>
{% endfor %}
{% endfor %}

上面的代码简化了原始版本,使事情变得更容易。

对于动态页面内容,最好的方法是使用 jquery 和 bootstrap。

呈现模板时,可以在第 10 个或后一个元素中添加类"d-none"(隐藏元素的内容(:

{% for post in post_queryset %}
<div name="comment-block">
<div class="title">
{{ post.title }}
</div>
{% for comment in post.comments.all %}
<div {% if forloop.counter > 9 %} class="d-none" {% endif %} >
{{ comment.text }}
</div>
{% endfor %}
<button type="button" name="more_comments" class="btn btn-primary" > more comments </button>
</div>
{% endfor %}

这样,将呈现所有注释,但仅显示前 10 条注释。

之后,由按钮单击触发的jquery函数应该可以解决问题

$("[name='more_comments']".click(function(){
var hidden_comments = $(this).parent().find('.d-none'); // selects all hidden comments
$(hidden_comments).each(function(){$(this).removeClass('d-none')}); // removes 'd-none' class
})

请记住,您的原始代码,无论是我的答案,都不符合引导程序,强烈建议您这样做。您可以在 https://getbootstrap.com/中了解有关引导程序的更多信息。

最新更新