曹阳的博客 仅用于学习和分享

分页功能的实现

2020-01-03

分页功能的实现

方法一:Django框架

视图函数blog.py

def list(request):
    # 先定义一个字典类型的返回内容
    u_dict = {}
    try:
        # 要加的key
        i = 0
        # 查询模型
        objs = Blog.objects.filter()
        # print(objs,'------------------------')

        # 2.实例化分页对象 参数1:数据集,参数2:每页显示的条数
        p = Paginator(objs, 3)
        # 6.接收当前的页码数
        inx_p = request.GET.get('page', 1)
        print(inx_p,'--------------------')
        # 3.获取当前页的数据
        b_dict = p.get_page(inx_p)
        # print(u_dict,'===================')
        # < Page 1 of 22 >

        # print(u_dict[2],'---------------')
        # Blog object(38)

        # id = u_dict[0].id
        # print(id,'-----------------')

        sjgs = p.count
        # print(sjgs,'------------------')  # 64
        ys = p.num_pages
        # print(ys,'================')  # 22

        end = sjgs%3
        # print(end,'-------------------')  # 1

        if p.page(inx_p).has_next():
            # 当前页不是最后一页
            for i in range(0, 3):
                u_dict[i] = b_dict[i]
                # print(u_dict,'=====================')
        else:
            for i in range(0, end):
                u_dict[i] = b_dict[i]
                # print(u_dict,'=====================')

        # print(u_dict,'=====================')
        # {0: < Blog: Blog object(34) >, 1: < Blog: Blog object(36) >, 2: < Blog: Blog object(38) >}

        # print(u_dict.values(),'----------------')
        # dict_values([<Blog: Blog object (34)>, <Blog: Blog object (36)>, <Blog: Blog object (38)>])

        for j in u_dict:
            id = u_dict[j].id
            name = u_dict[j].name
            link = u_dict[j].link
            img = settings.BASE_URL + u_dict[j].img
            description = u_dict[j].description
            title = u_dict[j].title

            uu_dict = {'id':id,'name':name,'link':link,'img':img,'description':description,'title':title}

            # print(uu_dict,'------------------')
            u_dict[j] = uu_dict
        # print(u_dict,'-------------------')
        # 接口测试成功了

        u_dict = {
            "status": "200",
            "info": "返回信息成功!",
            "data": u_dict,
            "contacts": u_dict
        }
    except:
        # u_dict = error_response(u_dict, "服务器错误,查询异常!")
        u_dict = {
            "status": "500",
            "info": "服务器错误,查询异常!",
            "data": u_dict,
            "contacts": u_dict
        }

    return JsonResponse(u_dict)

自定义标签templatetags/pagetag.py

from django import template
from django.utils.html import format_html

register = template.Library()

# 自定义加标签
@register.simple_tag
def jia(a, b):
    res = int(a) + int(b)
    return res


# 自定义乘标签
@register.simple_tag
def cheng(a, b):
    res = a * b
    # return res
    return '%.2f' % res


# 自定义分页优化标签
@register.simple_tag
def showpage(num, request):
    '''
        num 总页数
        p   当前页
    '''
    # 获取当前页码数
    p = int(request.GET.get('page', 1))

    # 获取当前页面的请求参数
    data = request.GET.dict()
    # print(data)
    # ?selecttype=phone&keywords=09
    # args = ''
    # for k, v in data.items():
    #     if k != 'page':
    #         args += f'&{k}={v}'
    # print(args)

    start = p - 5
    end = p + 4

    # 判断 当前页如果小于5
    if p <= 5:
        start = 1
        end = 10

    # 判断 当前页如果 大于 总页数-5
    if p > num - 4:
        start = num - 9
        end = num

    # 总页数 小于等于10
    if num <= 10:
        start = 1
        end = num
    s = ''
    s += f'<li><a href="?page=1">首页</a></li>'
    if p - 1 < 1:
        s += f'<li class="am-disabled"><a href="?page=1">上一页</a></li>'
    else:
        s += f'<li><a href="?page={p - 1}">上一页</a></li>'

    for x in range(start, end + 1):
        if x == p:
            s += f'<li class="am-active"><a href="?page={x}">{x}</a></li>'
        else:
            s += f'<li><a href="?page={x}">{x}</a></li>'

    if p + 1 > num:
        s += f'<li class="am-disabled"><a href="?page={num}">下一页</a></li>'
    else:
        s += f'<li><a href="?page={p + 1}">下一页</a></li>'
    s += f'<li><a href="?page={num}">尾页</a></li>'
    return format_html(s)

后台前端页面list.html

<div class="am-u-lg-12 am-cf">
	<div class="am-fr">
		<ul class="am-pagination tpl-pagination">
			<li>总页数:{ { data.paginator.num_pages } }</li>
			<li>总条数:{ { data.paginator.count } }</li>
			{ % load pagetag % }
			<!-- 使用自定义分z 页优化标签showpage data当前页的数据 paginator分页对象 num_pages获取总页数方法 request请求对象 -->
			{ % showpage data.paginator.num_pages request % }
		</ul>
	</div>
</div>

方法二:jQuery

blog.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Amaze UI Admin index Examples</title>
    <meta name="description" content="这是一个 index 页面">
    <meta name="keywords" content="index">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="renderer" content="webkit">
    <meta http-equiv="Cache-Control" content="no-siteapp"/>
    <link rel="icon" type="image/png" href="../../../assets/i/favicon.png">
    <link rel="apple-touch-icon-precomposed" href="../../../assets/i/app-icon72x72@2x.png">
    <meta name="apple-mobile-web-app-title" content="Amaze UI"/>
    <script src="../../../assets/js/echarts.min.js"></script>
    <link rel="stylesheet" href="../../../assets/css/amazeui.min.css"/>
    <link rel="stylesheet" href="../../../assets/css/amazeui.datatables.min.css"/>
    <link rel="stylesheet" href="../../../assets/css/app.css">
    <script src="../../../assets/js/jquery.min.js"></script>
    <script type="text/javascript" src="../../../assets/js/vue.js"></script>
    <script type="text/javascript" src="../../../assets/js/axios.min.js"></script>
    <style>
        .none{
            display: none;
        }
    </style>
</head>

<body onLoad="goPage(1,5)" data-type="widgets">
<script src="../../../assets/js/theme.js"></script>
<div class="am-g tpl-g">
	<div id="menu"></div>
    <!-- 内容区域 -->
    <div class="tpl-content-wrapper">
        <div class="row-content am-cf">
            <div class="row">
                <div class="am-u-sm-12 am-u-md-12 am-u-lg-12">
                    <div class="widget am-cf">
                        <div class="widget-head am-cf">
                            <div class="widget-title  am-cf">博客管理</div>
                        </div>
                        <div class="widget-body  am-fr">
                            <div class="am-u-sm-12 am-u-md-6 am-u-lg-6">
                                <div class="am-form-group">
                                    <div class="am-btn-toolbar">
                                        <div class="am-btn-group am-btn-group-xs">
                                            <button type="button" class="am-btn am-btn-default am-btn-success"><span class="am-icon-plus"></span> 新增
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="am-u-sm-12 am-u-md-12 am-u-lg-3">
                                <div class="am-input-group am-input-group-sm tpl-form-border-form cl-p">
                                    <input type="text" class="am-form-field ">
                                    <span class="am-input-group-btn">
                                            <button class="am-btn  am-btn-default am-btn-success tpl-table-list-field am-icon-search" type="button"></button>
                                        </span>
                                </div>
                            </div>
                            <div class="am-u-sm-12">
                                <div id="app">
                                    <table width="100%" class="am-table am-table-compact am-table-striped tpl-table-black" id="example-r">

<!--                                        <thead>-->
<!--                                            <th v-for="item,key,index in blog_title">{ { key } }</th>-->
<!--                                        </thead>-->

                                        <tbody v-for="item in blog">
                                            <tr v-if="item.id==first" class="gradeX">
                                                <td>id</td>
                                                <td>头像</td>
                                                <td>姓名</td>
                                                <td>链接</td>
                                                <td>标题</td>
                                                <td>描述</td>
                                                <td>操作</td>
                                            </tr>
                                            <tr>
                                                <td>{ { item.id } }</td>
                                                <td>
                                                    <img style="width: 100px;height: 100px;" :src="item.img" alt="">
                                                </td>
                                                <td>{ { item.name } }</td>
                                                <td>{ { item.link } }</td>
                                                <td>{ { item.title } }</td>
                                                <td>{ { item.description } }</td>
                                                <td>
                                                    <div class="tpl-table-black-operation">
														<a :id="item.id" href="javascript:;" @click="add">
															<i class="am-icon-pencil" @click.stop></i> 编辑
														</a>
                                                        <a :id="item.id" href="javascript:;"
                                                           class="tpl-table-black-operation-del" @click="del">
                                                            <i class="am-icon-trash"></i> 删除
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <!-- more data -->
                                        </tbody>
                                    </table>
                                    <table width="660px" height="100px" align="right">
                                        <tr>
                                            <td>
                                                <div id="barcon" name="barcon"></div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
<script src="../../../assets/js/amazeui.min.js"></script>
<script src="../../../assets/js/amazeui.datatables.min.js"></script>
<script src="../../../assets/js/dataTables.responsive.min.js"></script>
<script src="../../../assets/js/app.js"></script>
<script src="../../../assets/js/ming/学员风采/博客管理/list.js"></script>

<script type="">
    /**
     * 分页函数
     * pno--当前页数
     * psize--每页显示记录数
     * 分页部分是从真实数据行开始,因而存在加减某个常数,以确定真正的记录数
     * 纯js分页实质是数据行全部加载,通过是否显示属性完成分页功能
     **/

    function goPage2(pno,psize) {
        setTimeout(function () {
            goPage(pno, psize);
        },100)
    }

    function goPage(pno, psize) {

        var itable = document.getElementById("example-r");
        // console.log(12123123)
        var num = itable.rows.length;//表格所有记录数
        var pageSize = psize;//每页显示记录数
        //totalPage是总共分几页
        if (num / pageSize > parseInt(num / pageSize)) {
            var totalPage = parseInt(num / pageSize) + 1;
        } else {
            var totalPage = parseInt(num / pageSize);
        }
        var currentPage = pno;//当前页数
        var startRow = (currentPage - 1) * pageSize + 2;//开始显示的行
        var endRow = currentPage * pageSize;//结束显示的行
        endRow = (endRow > num) ? num : endRow;
        // console.log(endRow);
        // console.log(itable.rows)
        // 遍历显示数据实现分页
        for (var i = 2; i < (num + 1); i++) {
            var irow = itable.rows[i - 1];
             console.log(i+"ta")
            if (i >= startRow && i <= endRow) {
                irow.style.display = "table-row";
                // console.log(i+"table")
            } else {
                irow.style.display = "none";
                // console.log(i+"none")
            }
        }
        var tempStr = "共" + num + "条记录 共" + totalPage + "页 当前第" + currentPage + "页";

        if(totalPage == 0){

        }
        if (totalPage == 1 && currentPage == totalPage) {
            tempStr += "首页";
            tempStr += "上一页"
            tempStr += "currentPage"
            tempStr += "下一页";
            tempStr += "尾页";
        }
        if (currentPage == 1 && currentPage !== totalPage) {
            tempStr += "首页";
            tempStr += "上一页"
            tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage) + "," + pageSize + ")\">currentPage</a>"
            tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage + 1) + "," + psize + ")\">下一页></a>";
            tempStr += "<a href=\"#\" onClick=\"goPage(" + (totalPage) + "," + psize + ")\">尾页</a>";
        }else{
            if (currentPage == totalPage) {
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (1) + "," + psize + ")\">首页</a>";
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage - 1) + "," + psize + ")\">上一页</a>"
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage) + "," + pageSize + ")\">currentPage</a>"
                tempStr += "下一页";
                tempStr += "尾页";
            } else {
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (1) + "," + psize + ")\">首页</a>";
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage - 1) + "," + psize + ")\">上一页</a>"
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage) + "," + pageSize + ")\">currentPage</a>"
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (currentPage + 1) + "," + psize + ")\">下一页></a>";
                tempStr += "<a href=\"#\" onClick=\"goPage(" + (totalPage) + "," + psize + ")\">尾页</a>";
            }
        }

        document.getElementById("barcon").innerHTML = tempStr;
    }
</script>
</body>

</html>

Similar Posts

Content