溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

layui怎么實現(xiàn)數(shù)據(jù)表格并分頁

發(fā)布時間:2020-06-11 17:47:36 來源:億速云 閱讀:692 作者:鴿子 欄目:web開發(fā)

一.前端部分

html只需要放一個有id的div就行了,方便js獲取渲染區(qū)域

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

js部分需要注意url為異步數(shù)據(jù)接口,done是渲染完表格之后的回調函數(shù)

table.render({
            elem: '#data_grid'
            //,width: 900
            //,height: 274
            ,cols: [[ //標題欄
                {field: 'id', title: 'ID', width: 80, sort: true}
                ,{field: 'username', title:'用戶名',width: 100} //空列
                ,{field: 'password', title: '密碼', width: 120}
                ,{field: 'gender', title: '性別', width: 150}
                ,{field: 'nichen', title: '昵稱', width: 150}
                ,{field: 'birthday', title: '出生年月', width: 120}
                ,{fixed: 'right', width: 215,align:'center', toolbar: '#barDemo'}
            ]]
            ,url:url
            ,skin: 'row' //表格風格
            ,even: true
            ,page: true //是否顯示分頁
            ,limits: [3,5,10]
            ,limit: 5 //每頁默認顯示的數(shù)量
            ,done:function(res){
                userPage.data = res.data;
            }
            //,loading: false //請求數(shù)據(jù)時,是否顯示loading
        }); 

根據(jù)條件查詢,表格異步刷新,where為附帶參數(shù)

$('#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');
    //監(jiān)聽工具條
    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層需要接收以下參數(shù),page,limit,要查詢的條件,返回值根據(jù)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);   //根據(jù)條件查詢分頁數(shù)據(jù)

            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("數(shù)據(jù)獲取異常");
            return pageList;
        }

        return pageList;
    } 

Service層根據(jù)條件查詢并分頁

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沒有l(wèi)imit和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>

以上就是layui實現(xiàn)數(shù)據(jù)表格及分頁的方法的詳細內容,更多請關注億速云其它相關文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經查實,將立刻刪除涉嫌侵權內容。

AI