Django+Ajax实现 点击 加载更多

一些网站,例如带有评论的网站,一开始都会显示两条评论,当你点击"加载更多"的时候,页面会多显示几条;再点击,会再会多显示几条。那么,就会只有评论区在变动,就需要进行Ajax请求。
一开始,在页面中的函数中,显示2条评论信息:

def detail(request,article_id):
    # 当用户点击了一次加载更多评论之后(显示4条评论),点完以后,用户又提交了新的评论,评论之后页面会重定向到详情页,所以comments = article.comment_set.all()[0:2]这个查询就需要是动态变化的。
    article = Article.objects.get(id=article_id)
    comment_form = CommentForm()
    offset = int(request.COOKIES.get('offset',2))
    comments = article.comment_set.all()[0:offset]
    return render(request,'article_page.html',locals())

在html中,写一个“点击加载更多”的a标签

<a href="#" id="more">...加载更多</a>

然后,写js代码:

<script>
        String.prototype.format= function() {
            if(arguments.length === 0) return this;
            var param = arguments[0], str= this;
            if(typeof(param) === 'object') {
                for(var key in param)
                    str = str.replace(new RegExp("\\{" + key + "\\}", "g"), param[key]);
                return str;
            } else {
                for(var i = 0; i < arguments.length; i++)
                    str = str.replace(new RegExp("\\{" + i + "\\}", "g"), arguments[i]);
                return str;
            }
        };

        {# offset:是需要传给后台的参数,用于获取评论的参数,评论的偏移量,此请求应该从索引为2的位置开始获取,默认索引为0,1的评论已经展示过了。 #}
        offset = parseInt('{{ offset }}');
        $('#more').click(function () {
            offset += 2;
            $('input[name="offset"]').val(offset);
            $.ajax({
                url:'{% url 'more' %}',
                data:{
                    'offset':offset,
                    'article_id':'{{ article.id }}'
                },
                success:function (data,status) {
                    {# data这个参数是后台返回的数据,此时后台需要返回JSON字符串;并将相应的结果展示在页面中。 #}
                    {#console.log(data,status)#}
                    var comments = data['comments'];
                    for(var i=0;i<comments.length;i++) {
                        {# 利用i为索引,从comments数组中获取对应的评论内容 #}
                        var comment = comments[i];
                        {# 利用js向页面中插入两条评论 #}
                        result = '<div class="row"><article class="col-xs-12"><p class="pull-right"><span class="label label-primary">{date}</span> <span class="label label-default">{user}</span></p><a class="pull-right" href="/blog_poll/{article.id}/?comment_id={comment_id}"><span class="glyphicon glyphicon-thumbs-up"></span>{poll_num}</a><p>{content}</p></article></div><hr>'.format(comment);
                        {# $(this)指的就是$('more'),表示获取当前操作的对象。before():指的就是在当前元素前面追加两个元素 #}
                        $('#more').before(result);
                    }
                }
            });
            {# return false:阻止a标签的默认的GET请求事件。 #}
            return false;

        })
    </script>

路由more对应的函数:

from django.http import HttpResponse,JsonResponse
def more(request):
    # 获取前端传过来的评论偏移量
    offset = int(request.GET.get('offset'))
    # 根据这个偏移量查询出来两条评论,需要先获取当前这个文章的额所有评论
    article = Article.objects.get(id=request.GET.get('article_id'))
    comments = article.comment_set.all()[offset-2:offset]
    # 将要展示的评论转换成json字符串,返回给前端。{'comments':[{评论id,评论内容...},{},{}]}
    comments_dict={}
    comments_list = []
    for comment in comments:
        dic = {}
        dic['content'] = comment.content
        article_date = str(comment.date.year) + '年' + str(comment.date.month) + '月'+ str(comment.date.day) + '日'+' '+ str(comment.date.hour) + ':' + str(comment.date.minute)
        dic['date'] = article_date
        dic['poll_num'] = comment.poll_num
        dic['user'] = comment.user.uname
        dic['article_id'] = comment.article.id
        dic['comment_id'] = comment.id
        comments_list.append(dic)
    comments_dict['comments'] = comments_list
    response = JsonResponse(comments_dict)
    response.set_cookie('offset',offset)
    return response

但是,当首页进来的时候,offset应该还是2

def index(request):
    '''
    功能:1.查询所有文章 2.渲染LoginForm登录的输入框
    :param request:
    :return:
    '''

    login_form = LoginForm()
    articles = Article.objects.all()
    resposne = render(request,'index.html',locals())
    resposne.set_cookie('offset',2)
    return resposne

一开始两条:
在这里插入图片描述
点击加载更多:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/zhangmengran/article/details/84072755