首页 > 解决方案 > 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 %}

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

标签: djangodjango-paginationdjango-comments

解决方案


对于动态页面内容,最好的方法是使用 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
    })

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


推荐阅读