zoukankan      html  css  js  c++  java
  • layui数据表格及分页

    一.前端部分

    html只需要放一个有id的div就行了,方便js获取渲染区域

    <div id="data_grid" lay-filter="demo" ></div>  

    js部分需要注意url为异步数据接口,done是渲染完表格之后的回调函数

    table.render({
                elem: '#data_grid'
                //, 900
                //,height: 274
                ,cols: [[ //标题栏
                    {field: 'id', title: 'ID',  80, sort: true}
                    ,{field: 'username', title:'用户名', 100} //空列
                    ,{field: 'password', title: '密码',  120}
                    ,{field: 'gender', title: '性别',  150}
                    ,{field: 'nichen', title: '昵称',  150}
                    ,{field: 'birthday', title: '出生年月',  120}
                    ,{fixed: 'right',  215,align:'center', toolbar: '#barDemo'}
                ]]
                ,url:url
                ,skin: 'row' //表格风格
                ,even: true
                ,page: true //是否显示分页
                ,limits: [3,5,10]
                ,limit: 5 //每页默认显示的数量
                ,done:function(res){
                    userPage.data = res.data;
                }
                //,loading: false //请求数据时,是否显示loading
            }); 

    根据条件查询,表格异步刷新,where为附带参数

    $('#sub_query_form').on('click',function () {
            var queryPo = page.formToJson($('#query_form').serialize());
            var table = layui.table;
            table.reload('data_grid', {
                url: '/getUserList.action',
                page:{
                    curr:1  //从第一页开始
                },
    
                method:'post',
                where:{
                    queryStr:queryPo
                },
                done:function (res) {
                    userPage.data = res.data;
                }
            });
        }); 

    将x-www-form-urlencoded转化为json字符串

    formToJson:function (data) {
            data=data.replace(/&/g,"","");
            data=data.replace(/=/g,"":"");
            data="{""+data+""}";
            return data;
        }

    表格工具栏使用

    1.首先在html里定义好按钮

    <script type="text/html" id="barDemo">
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="add">增加</a>
            <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>

    2.js内引用

    layui.use('table', function(){
        var table = layui.table;
        userPage.tab('/getUserList.action');
        //监听工具条
        table.on('tool(demo)', function(obj){
            var data = obj.data;
            userPage.data = obj.data;
            if(obj.event === 'detail'){
                layer.msg('ID:'+ data.id + ' 的查看操作');
            }
            else if(obj.event === 'del'){
                layer.confirm('真的要删除这条记录么',{icon: 3, title:'确定删除'}, function(index){
                    obj.del();
                    $.post('/doDelete.action?id='+data.id,function (res) {
                        userPage.reload(res);
                    });
                    layer.close(index);
                });
    
            }
            else if(obj.event === 'add'){
               layer.open({
                   title:'增加窗口',
                   content:userPage.template,
                   yes:function () {
                       var user = page.formToJson($('#layer_form').serialize());
                       var data = 'user='+user;
                      $.post('/doAdd.action',data,function (res) {
                          userPage.reload(res);
                      });
                      layer.closeAll();
                   }
               })
    
            }
            else if(obj.event === 'edit'){
                layer.open({
                    title:'编辑窗口',
                    content:userPage.template,
                    success:function () {
                        $('input[name="id"]').val(userPage.data.id);
                        $('input[name="username"]').val(userPage.data.username);
                        $('input[name="password"]').val(userPage.data.password);
                        $('input[name="gender"]').val(userPage.data.gender);
                        $('input[name="nichen"]').val(userPage.data.nichen);
                        $('input[name="birthday"]').val(userPage.data.birthday);
                    },
                    yes: function(){
                        var mgUser = page.formToJson($('#layer_form').serialize());
                        var data = 'user='+mgUser;
                        $.post('/doEdit.action',data,function (res) {
                            userPage.reload(res);
                        });
                        layer.closeAll();
                    }
                })
            }
        });
    });

    二.服务端部分 

    Controller层需要接收以下参数,page,limit,要查询的条件,返回值根据layui文档给出的默认返回值

     @RequestMapping("/getUserList")
        @ResponseBody
        public PageList<MgUser> getUserList(@RequestParam(required = false,defaultValue = "1") int page,@RequestParam(required = false,defaultValue = "5") int limit,@RequestParam(required = false) String queryStr){
            QueryPo queryPo = null;
            if (!StringUtils.isEmpty(queryStr)){   //性别类型转换
                 queryPo = JSONObject.parseObject(queryStr,QueryPo.class);
                if ("1".equals(queryPo.getGender())){
                    queryPo.setGender("男");
                }
                if ("2".equals(queryPo.getGender())){
                    queryPo.setGender("女");
                }
    
            }
            PageList pageList = new PageList();
            try {
                if (!StringUtils.isEmpty(queryPo)){ //中文字转码
                    if(!StringUtils.isEmpty(queryPo.getKeywords())){
                        queryPo.setKeywords(URLDecoder.decode(queryPo.getKeywords(),"utf-8"));
                    }
                }
                List<MgUser> userList = userService.getUserList(page,limit,queryPo);   //根据条件查询分页数据
    
                pageList.setCode("0");
                pageList.setMsg("ok");
                pageList.setData(userList);
                int count = userService.countUserByExample(queryPo);
                pageList.setCount(count);
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                pageList.setCode("-1");
                pageList.setMsg("数据获取异常");
                return pageList;
            }
    
            return pageList;
        } 

    Service层根据条件查询并分页

    public List<MgUser> getUserList(int page , int limit, QueryPo queryPo) {
            MgUserExample userExample = new MgUserExample();
            MgUserExample.Criteria criteria = userExample.createCriteria();
            if(!StringUtils.isEmpty(queryPo)){
                if (!StringUtils.isEmpty(queryPo.getGender())){
                    criteria.andGenderEqualTo(queryPo.getGender());
                }
                if (!StringUtils.isEmpty(queryPo.getKeywords())){
                    criteria.andUsernameLike("%"+queryPo.getKeywords()+"%");
                }
            }
    
            userExample.setStart((page-1)*limit);
            userExample.setLimit(limit);
    
            List<MgUser> mgUsers = userMapper.selectByExample(userExample);
    
            return mgUsers;
        } 

    注意由于mybatis逆向工程生成的Example没有limit和page,所以需要自己加上

        private int start;
        private int limit;
        
        public int getStart() {
            return start;
        }
    
        public void setStart(int start) {
            this.start = start;
        }
    
        public int getLimit() {
            return limit;
        }
    
        public void setLimit(int limit) {
            this.limit = limit;
        }

    接着修改Mybatis的mapper.xml,需要加上分页条件

    <select id="selectByExample" resultMap="BaseResultMap" parameterType="com.wang.entity.MgUserExample" >
        select
        <if test="distinct" >
          distinct
        </if>
        <include refid="Base_Column_List" />
        from mg_user
    
        <if test="_parameter != null" >
          <include refid="Example_Where_Clause" />
        </if>
        <if test="orderByClause != null" >
          order by ${orderByClause}
        </if>
        <if test="start !=0 or limit!=0">
          limit #{start},#{limit}
        </if>
      </select>

     

  • 相关阅读:
    Atitit attilax要工作研究的要素 纪要 方案 趋势 方向 概念 理论
    Atitit 常见每日流程日程日常工作.docx v7 r8f
    Atitit it 互联网 软件牛人的博客列表
    Atitit 信息链(Information Chain)的概念理解 attilax总结
    Atitit 知识点的体系化 框架与方法 如何了解 看待xxx
    Atitit 聚合搜索多个微博 attilax总结
    Atitit 企业知识管理PKM与PIM
    Atitit 项目沟通管理 Atitit 沟通之道 attilax著.docx
    Atitit 项目管理软件 在线服务 attilax总结 1. 项目管理协作的历史 1 1.1. Worktile 406k 1 1.2. Teambition  584k in baidu
    Atitit.每周末总结 于每周一计划日程表 流程表 v8 import 上周遗漏日志补充 检查话费 检查流量情况 Crm问候 Crm表total and 问候
  • 原文地址:https://www.cnblogs.com/wangxiayun/p/9145638.html
Copyright © 2011-2022 走看看