Home > Backend Development > PHP Tutorial > layui implements paging of dynamic and static data tables

layui implements paging of dynamic and static data tables

不言
Release: 2023-03-25 13:40:02
Original
6410 people have browsed it

This article mainly introduces the implementation of dynamic and static data table paging in layui. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

The development management background is every development This is a link that everyone should be familiar with. As back-end programmers, all the company’s confidential data is in our hands, so at this time, if you are not a core member of the company, you cannot access certain data. At this time, all the confidential data of the company are in our hands. All the work fell into our hands, from PS to Linux, we needed to do it ourselves. Fortunately, we discovered layui, a front-end framework, which relieved our pressure to a great extent.

Today we will first learn layui to implement dynamic data tables, static data tables, and table paging, which also involves dynamic refresh of data tables, use of data table toolbars, and form submission This static paging is also applicable to information websites. My working development environment is the debian desktop version, so all experiments are also tested on the basis of debian

layui dynamic data table

Rendering of dynamic data table

layui implements paging of dynamic and static data tables

##Implementation process

I have all the business logic I wrote it in the comments, so that everyone can be more friendly and avoid being easily distracted by looking at the code for a while and the instructions for a while.

Front-end code:

  • head.phtml (header file code)

  • <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <title><?php echo $curTitle;?></title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="format-detection" content="telephone=no">
        <link rel="stylesheet" href="static/css/layui.css" media="all">
        <link rel="stylesheet" href="static/css/globals.css" media="all">
        <script src="static/layui.js" charset="utf-8"></script>
        <!--引入自定义模块全局配置文件-->
        <script src="static/global.js" charset="utf-8"></script>
    </head>
    <body class="layui-layout-body">
    Copy after login
  • order_orderlist.phtml (main business code)

  • <?php $this->import("head"); ?>
    <p class="layui-fluid">
        <blockquote class="layui-elem-quote">注意:为保障访问速度,查询同时请配合时间范围,默认显示一天以内的记录</blockquote>
        <br/>
        <p class="layui-form-item layui-form-pane">
            <p class="layui-inline">
                <label class="layui-form-label" style="width: 85px;">商户号</label>
                <p class="layui-input-inline" style="width: 165px;">
                    <input type="text" name="merchant_no" autocomplete="off" class="layui-input">
                </p>
            </p>
            <p class="layui-inline">
                <label class="layui-form-label" style="width: 85px;">订单号:</label>
                <p class="layui-input-inline" style="width: 165px;">
                    <input type="text" name="order_no" autocomplete="off" class="layui-input">
                </p>
            </p>
            <p class="layui-inline">
                <label class="layui-form-label" style="width: 95px;">发起时间</label>
                <p class="layui-input-inline" style="width: 165px;">
                    <input type="text" class="layui-input" name="start_time" id="test5" placeholder="yyyy-MM-dd HH:mm:ss">
                </p>
                <p class="layui-form-mid">-</p>
                <p class="layui-input-inline" style="width: 165px;">
                    <input type="text" class="layui-input" name="end_time" id="test6" placeholder="yyyy-MM-dd HH:mm:ss">
                </p>
            </p>
            <p class="layui-inline">
                <button id="fuck-btn" class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon">&#xe615;</i>查询</button>
                <button id="reloadtable" class="layui-btn layui-btn-normal"><i class="layui-icon">&#x1002;</i>刷新数据</button>
                <button id="reloadpage" class="layui-btn layui-btn-normal"><i class="layui-icon">&#x1002;</i>刷新页面</button>
            </p>
        </p>
    <table class="layui-hide" id="test"></table>
    </p>
    <script>
        // 加载需要用到的模块,如果有使用到自定义模块也在此加载
        layui.use([&#39;laydate&#39;,&#39;form&#39;,&#39;table&#39;], function(){
            // 初始化元素,如果有大量的元素操作可以也引入和初始化element模块
            var table = layui.table;
            var form = layui.form;
            var laydate = layui.laydate;
            var $ = layui.$;
            // 定义时间选择器
            laydate.render({
                elem:&#39;#test5&#39;,
                type:&#39;datetime&#39;
            });
            laydate.render({
                elem:&#39;#test6&#39;,
                type:&#39;datetime&#39;
            });
            // 动态数据表渲染
            table.render({
                 elem: &#39;#test&#39;                            /* 绑定表格容器id */
                ,url:&#39;index.php?c=orders&a=orderList&#39;     /* 获取数据的后端API URL */
                ,where:{getlist:&#39;orderlist&#39;}              /* 这里还可以额外的传参到后端 */
                ,method: &#39;post&#39;                           /* 使用什么协议,默认的是GET */
                ,cellMinWidth: 60                         /* 最小单元格宽度 */
                ,cols: [[
                     {field:&#39;orderno&#39;, title: &#39;订单号&#39;,align: &#39;center&#39;,sort:true}
                    ,{field:&#39;username&#39;, title: &#39;商户号&#39;,align: &#39;center&#39;}
                    ,{field:&#39;user_orderno&#39;, title: &#39;商户订单号&#39;,align: &#39;center&#39;}
                    ,{field:&#39;trace_time&#39;, title: &#39;创建时间&#39;,align: &#39;center&#39;,sort:true,width:200}
                    ,{field:&#39;price&#39;, title: &#39;交易金额&#39;,align: &#39;center&#39;,sort:true}
                    ,{field:&#39;fee&#39;, title: &#39;手续费&#39;,align: &#39;center&#39;,sort:true,width:80}
                    ,{field:&#39;real_price&#39;, title: &#39;结算金额&#39;,align: &#39;center&#39;,sort:true}
                    ,{field:&#39;pay_type&#39;, title: &#39;支付类型&#39;, align: &#39;center&#39;}
                    ,{field:&#39;pay_status&#39;, title: &#39;订单状态&#39;,align: &#39;center&#39;,width:90}
                    ,{field:&#39;pay_time&#39;, title: &#39;支付时间&#39;,align: &#39;center&#39;,sort:true,width:200}
                    ,{field:&#39;push_nums&#39;, title: &#39;通知次数&#39;,align: &#39;center&#39;,width:90}
                    ,{field:&#39;notice_result&#39;, title: &#39;通知支付结果&#39;,align: &#39;center&#39;}
                ]]    // 使用sort将自动为我们添加排序事件,完全不用人工干预
                ,page: true
                ,limit:10
                ,id:&#39;testReload&#39; // 这里就是重载的id
            });
            // 数据表重载,这个是配合上面的表格一起使用的
            var active = {
                reload:function(){
                    table.reload(&#39;testReload&#39;,{
                       // 点击查询和刷新数据表会把以下参数传到后端进行查找和分页显示
                        where:{
                            merchant_no:$("input[name=&#39;merchant_no&#39;]").val(),
                            order_no: $("input[name=&#39;order_no&#39;]").val(),
                            start_time:$("input[name=&#39;start_time&#39;]").val(),
                            end_time:$("input[name=&#39;end_time&#39;]").val()
                        }
                    });
                }
            };
            
            form.render(); // 渲染表单
            // 查找点击时间,这里的事件绑定建议使用on来绑定,因为元素都是后期渲染过的
            $("#fuck-btn").click(function(){
                var type = $(this).data(&#39;type&#39;);
                active[type] ? active[type].call(this) : &#39;&#39;;
            });
            $("#reloadtable").click(function(){
                active.reload();
            });
            $("#reloadpage").click(function(){
                location.reload();
            });
        });
    </script>
    </body>
    </html>
    Copy after login

Backend php code

    ##order.php (order controller, some business codes don’t need to be studied too deeply)
  •     // 订单列表
        public function orderList()
        {
            // 动态渲染前台表格
            $operating = $this->request->getPost(&#39;getlist&#39;, &#39;trim&#39;);
            // 首次这里不会执行,数据表开始渲染的时候才会请求以下部分
            if (&#39;orderlist&#39; === $operating) {
                // 进行分页查询
                $page = $this->request->getPost(&#39;page&#39;, &#39;intval&#39;, 1);
                $limit = $this->request->getPost(&#39;limit&#39;, &#39;intval&#39;, 10);
                $start = ($page - 1) * $limit;
    
                // 如果有其他条件查询在这里可以带上
                $merchant_no = $this->request->getPost(&#39;merchant_no&#39;, &#39;trim&#39;, &#39;&#39;);
                $order_no = $this->request->getPost(&#39;order_no&#39;, &#39;trim&#39;, &#39;&#39;);
                $start_time = $this->request->getPost(&#39;start_time&#39;, &#39;trim&#39;, date("Y-m-d H:i:s", strtotime("-1 day")));
                $end_time = $this->request->getPost(&#39;end_time&#39;, &#39;trim&#39;, date("Y-m-d H:i:s"), time());
    
                // 获取符合条件的记录数量
                if($GLOBALS[&#39;SESSION&#39;][&#39;admin_group_id&#39;] >1){
                    $merchant_no = $GLOBALS[&#39;SESSION&#39;][&#39;admin_username&#39;];
                }
                $order_nums = orders::getItemNums($merchant_no, $order_no, $start_time, $end_time);
    
                // 分页进行查询条件记录
                $order_list = orders::getItem($merchant_no, $order_no, $start_time, $end_time, $start, $limit);
                $datas = [&#39;code&#39; => 0, &#39;msg&#39; => &#39;&#39;];
                // 将总的记录条数传给前台进行渲染分页
                $datas[&#39;count&#39;] = $order_nums;
                // 重新过滤一遍数据,很多没有用到的不能全部发给试图,尤其是动态渲染的,很容易暴露,建议加工一下再传
                foreach ($order_list as $k => $v) {
                    $order_list[$k][&#39;orderno&#39;] = $v[&#39;order_id&#39;];
                    $order_list[$k][&#39;user_orderno&#39;] = $v[&#39;order_no&#39;];
                    $order_list[$k][&#39;username&#39;] = $v[&#39;merchant_no&#39;];
                    $order_list[$k][&#39;pay_type&#39;] = ($v[&#39;pay_type&#39;] == 1) ? "支付宝扫码" : "微信扫码";
                    $order_list[$k][&#39;pay_status&#39;] = ($v[&#39;callback_status&#39;] > 0) ? "已支付" : "未支付";
                    $order_list[$k][&#39;pay_time&#39;] = $v[&#39;callback_time&#39;];
                    $order_list[$k][&#39;notice_result&#39;] = ($v[&#39;push_status&#39;] > 0) ? "<span class=\"layui-badge layui-bg-blue\">已推送</span>" : "<span class=\"layui-badge layui-bg-gray\">未推送</span>";
                }
                // 将数据通过json格式响应给前台渲染
                $datas[&#39;data&#39;] = $order_list;
                echo json_encode($datas);
                safe_exit();
            }
            // 首次先现实模板页
            self::$view->render(&#39;orders_orderlist&#39;);
        }
    Copy after login
  • Please refer to the official guidance for data format: data interface format, table module
When debugging, you can open

console
and network# of chrome, firefox ##Check and carefully study and analyzeData table toolbar events

Toolbar refers to the corresponding row that can be operated in the row cell, because

layui

is used Element monitoring makes it easy to obtain data corresponding to the entire row.

For example, to obtain form data, you only need to listen to the form submission event, and you can directly obtain all parameters and values ​​at once: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">&lt;script&gt; layui.use([&amp;#39;form&amp;#39;,&amp;#39;jquery&amp;#39;],function(){ let form = layui.form, $ = layui.$; form.on(&amp;#39;submit(fuck-submit)&amp;#39;, function(data){ if(data.field.password &amp;&amp; data.field.password.length &lt; 5){ layer.msg(&amp;#39;密码不能小于5位&amp;#39;); return false; } $.post(&amp;#39;index.php?&amp;a=adminEdit&amp;op=update&amp;uid=&amp;#39;+data.field.uid,{ username:data.field.username, password:data.field.password, level:data.field.level, is_enabled:data.field.is_enabled }, function(responseText){ //console.log(responseText); if(responseText.errno === 8){ layer.msg(responseText.errstr,{icon:6}); return false; } else { layer.msg(responseText.errstr,{icon:5}); location.reload(); } },&amp;#39;json&amp;#39; ); return false; }); }); &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div> Here is the official document:

form.on(&#39;submit(*)&#39;, function(data){
  console.log(data.elem) //被执行事件的元素DOM对象,一般为button对象
  console.log(data.form) //被执行提交的form对象,一般在存在form标签时才会返回
  console.log(data.field) //当前容器的全部表单字段,名值对形式:{name: value}
  return false; //阻止表单跳转。如果需要表单跳转,去掉这段即可。
});
Copy after login

The data table we are going to operate today also uses this method. First, let’s take a look at how to generate and render the toolbar:


layui implements paging of dynamic and static data tablesYou only need to insert a container in the body part. Note that the type

of

javascript here is text/html, this is forlayuiIt is used for analysis. The d here is the data when we render the form. The values ​​of all fields can be obtained in this d

    <table class="layui-hide" lay-filter="fucktest" id="test"></table>
    <script type="text/html" id="barDemo">
        <a class="layui-btn layui-btn-xs" user_id="{{d.admin_id}}" lay-event="edit">编辑</a>
    </script>
Copy after login
 // 这里就是我们渲染表格字段的地方,和上面的容器进行绑定,容器里面可以通过d.fixed来获取到
 {fixed: &#39;right&#39;, width:158,title:&#39;操作&#39;, align:&#39;center&#39;, toolbar: &#39;#barDemo&#39;}
Copy after login
Then we can bind events to the toolbar. Here I only use the edit event
table.on(&#39;tool(fucktest)&#39;, function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
            var tr = obj.tr; //获得当前行 tr 的DOM对象

            if(layEvent === &#39;detail&#39;){ //查看
                //do somehing
            } else if(layEvent === &#39;del&#39;){ //删除
                layer.confirm(&#39;真的删除行么&#39;, function(index){
                    obj.del(); //删除对应行(tr)的DOM结构,并更新缓存
                    layer.close(index);
                    //向服务端发送删除指令
                });
            } else if(layEvent === &#39;edit&#39;){ //编辑
                    // 开始根据用户id来进行获取用户进入新窗口
                var index = layer.open({
                    type: 2,
                    title:&#39;编辑管理员&#39;,
                    area: [&#39;700px&#39;, &#39;560px&#39;],
                    maxmin: true,
                    content: &#39;index.php?c=adminUser&a=editUser&uid=&#39;+data.admin_id
                });
                layer.full(index);

            }
        })
Copy after login

so that the corresponding event can be activated after clicking edit. Here we open a new full-screen pop-up window. Modify administrator information


layui implements paging of dynamic and static data tablesAfter the modification is completed, if you just want to simply reload the data table, you can use the method we used earlier. If you want to refresh the page, use it directlylocation.reload()

       // 重载数据表
       var active = {
            reload:function(){
                var demoReload = $("#demoReload");
                var dateReload = $("#dateReload");
                table.reload(&#39;testReload&#39;,{
                    where:{
                        username:demoReload.val(),
                        dates:dateReload.val()
                    }
                });
            }
        };
        $("#fresh-btn").click(function(){active.reload();});
        $("#fresh-page-btn").click(function(){location.reload();});
Copy after login
Here is the official example toolbar-binding column toolbar

The template corresponding to toolbar, which can be stored anywhere on the page:

  <script type="text/html" id="barDemo">
  <a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>
  <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
  
  <!-- 这里同样支持 laytpl 语法,如: -->
  {{#  if(d.auth > 2){ }}
    <a class="layui-btn layui-btn-xs" lay-event="check">审核</a>
  {{#  } }}
</script>
 
注意:属性 lay-event="" 是模板的关键所在,值可随意定义。
Copy after login

Rendering toolbar:

table.render({
  cols: [[
    {field:&#39;id&#39;, title:&#39;ID&#39;, width:100}
    ,{fixed: &#39;right&#39;, width:150, align:&#39;center&#39;, toolbar: &#39;#barDemo&#39;} //这里的toolbar值是模板元素的选择器
  ]]
});
 
等价于:
<th lay-data="{field:&#39;id&#39;, width:100}">ID</th>
<th lay-data="{fixed: &#39;right&#39;, width:150, align:&#39;center&#39;, toolbar: &#39;#barDemo&#39;}"></th>
Copy after login

Toolbar binding event:

//监听工具条
table.on(&#39;tool(test)&#39;, function(obj){ //注:tool是工具条事件名,test是table原始容器的属性 lay-filter="对应的值"
  var data = obj.data; //获得当前行数据
  var layEvent = obj.event; //获得 lay-event 对应的值(也可以是表头的 event 参数对应的值)
  var tr = obj.tr; //获得当前行 tr 的DOM对象
 
  if(layEvent === &#39;detail&#39;){ //查看
    //do somehing
  } else if(layEvent === &#39;del&#39;){ //删除
    layer.confirm(&#39;真的删除行么&#39;, function(index){
      obj.del(); //删除对应行(tr)的DOM结构,并更新缓存
      layer.close(index);
      //向服务端发送删除指令
    });
  } else if(layEvent === &#39;edit&#39;){ //编辑
    //do something
    
    //同步更新缓存对应的值
    obj.update({
      username: &#39;123&#39;
      ,title: &#39;xxx&#39;
    });
  }
});
Copy after login

For a more detailed introduction, please read the official documentation carefully layui table module

Static table And paging

In many cases, excessive use of dynamic rendering on the

pc

end is not a wise choice. For example, anyone with a little knowledge can see your
API and the required param, so we still recommend using static tables for programs with higher security requirements, whether through template engines, or directly using back-end dynamic language mixing. Users can only see it in the end. The parsed page is also necessary for program protection. One of my hacker friends exploits loopholes in this way when performing penetrationI directly use the static form herephp
Mixed parsing for display:

Front-end template:

index.php
  • <?php $this->import(&#39;head&#39;);?>
    <body>
    <blockquote class="layui-elem-quote">注意:此处仅显示部分日志</blockquote>
    <table class="layui-table" lay-size="sm">
        <colgroup>
        </colgroup>
        <thead>
        <tr>
            <th>日志ID</th>
            <th>操作用户</th>
            <th>操作</th>
            <th>控制器</th>
            <th>方法</th>
            <th>是否成功</th>
            <th>操作IP</th>
            <th>备注信息</th>
            <th>日期</th>
        </tr>
        </thead>
        <tbody>
        <?php foreach($log_list as $kk => $vv):?>
        <tr>
            <td><?php echo $vv[&#39;log_id&#39;];?></td>
            <td><?php echo $vv[&#39;username&#39;];?></td>
            <td><?php echo $vv[&#39;title&#39;];?></td>
            <td><?php echo $vv[&#39;control&#39;];?></td>
            <td><?php echo $vv[&#39;action&#39;];?></td>
            <td><?php echo $vv[&#39;is_success&#39;];?></td>
            <td><?php echo $vv[&#39;client_ip&#39;];?></td>
            <td><?php echo $vv[&#39;remark&#39;];?></td>
            <td><?php echo $vv[&#39;date&#39;];?></td>
        </tr>
        <?php endforeach;?>
        </tbody>
    </table>
    <p id="test1"></p>
    <script src="js/layui/layui.js"></script>
    <script>
        layui.use(&#39;laypage&#39;, function(){
            var laypage = layui.laypage;
            laypage.render({
                elem: &#39;test1&#39; //注意,这里的 test1 是 ID,不用加 # 号
                ,count: <?php echo $log_num;?> // 数据总数,从服务端得到
                ,curr: <?php echo $currpage;?> // 服务器端回传当前页
                ,jump: function(obj, first){
                    //obj包含了当前分页的所有参数,比如:
                    console.log(obj.curr);  //得到当前页,以便向服务端请求对应页的数据。
                    console.log(obj.limit); //得到每页显示的条数
                    //首次不执行,使用原始的curr,后面需要自己通过回传来更新
                    var curr = obj.curr;
                    if(!first){
                        location.href=&#39;index.php?&a=adminLogList&page=&#39;+obj.curr;
                    }
                }
            });
        });
    </script>
    
    </body>
    <?php $this->import(&#39;foot&#39;);?>
    Copy after login

    The principle here is very simple , mainly using the
  • laypage
module under

layui, using jump to trigger events

adminLogList method:
       public function adminLogList()
        {   // 接收当前页,如果没有收到默认是第一页
            $page = $this->request->getGet(&#39;page&#39;,&#39;intval&#39;,1);
            // 设置limit查找起始,DEFAULT_PER_PAGE为全局变量,设置的是每页显示10条
            $start = ($page-1)*DEFAULT_PER_PAGE;
            // 获取总日志数量
            $adminlog_num = adminLogs::getItemsNumber();
            // 分页查找,其他查询条件暂时不传
            $admin_log_list = adminLogs::getItems(&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,&#39;&#39;,$start);
            $log_list = array();
            foreach($admin_log_list as $kk => $vv){
                if($vv[&#39;admin_id&#39;] > 0){
                    try{
                        $admins = admins::getItemById($vv[&#39;admin_id&#39;]);
                        $log_list[$kk][&#39;username&#39;] = $admins[&#39;username&#39;];
                    } catch (exception2 $e){
                        logexception($e->format_stack_trace());
                    }
                } else {
                    $log_list[$kk][&#39;username&#39;] = &#39;Tourists&#39;;
                }
                $log_list[$kk][&#39;log_id&#39;] = $vv[&#39;log_id&#39;];
                $log_list[$kk][&#39;control&#39;] = $vv[&#39;control&#39;];
                $log_list[$kk][&#39;action&#39;] = $vv[&#39;action&#39;];
                $log_list[$kk][&#39;is_success&#39;] = $vv[&#39;is_success&#39;];
    
                $log_list[$kk][&#39;client_ip&#39;] = ip2location($vv[&#39;client_ip&#39;]);
                $log_list[$kk][&#39;remark&#39;] = $vv[&#39;remark&#39;];
                $log_list[$kk][&#39;date&#39;] = $vv[&#39;date&#39;];
                $log_list[$kk][&#39;title&#39;] = $vv[&#39;title&#39;];
                unset($admin_log_list[$kk]);
            }
            self::$view->setVar(&#39;currpage&#39;,$page);
            self::$view->setVar(&#39;log_num&#39;,$adminlog_num);
            self::$view->setVar(&#39;log_list&#39;,$log_list);
            self::$view->render(&#39;default_addloglist&#39;);
        }
    Copy after login

    最终效果,已经完成静态分页,此部分功能也适用于信息类网站:
    layui implements paging of dynamic and static data tables

    相关推荐:

    layui实现动态和静态分页


    The above is the detailed content of layui implements paging of dynamic and static data tables. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template