Home Web Front-end Layui Tutorial Layui's method of implementing data tables and paging

Layui's method of implementing data tables and paging

Jun 11, 2020 pm 05:25 PM
layui

Layui's method of implementing data tables and paging

1. The front-end part

html only needs to put a div with an id, which is convenient for js to obtain the rendering area

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

The js part needs attention url is an asynchronous data interface, done is the callback function after rendering the form

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

Query according to conditions, the table is refreshed asynchronously, where is the attached parameter

$(&#39;#sub_query_form&#39;).on(&#39;click&#39;,function () {
        var queryPo = page.formToJson($(&#39;#query_form&#39;).serialize());
        var table = layui.table;
        table.reload(&#39;data_grid&#39;, {
            url: &#39;/getUserList.action&#39;,
            page:{
                curr:1  //从第一页开始
            },

            method:&#39;post&#39;,
            where:{
                queryStr:queryPo
            },
            done:function (res) {
                userPage.data = res.data;
            }
        });
    }); 
Copy after login

Convert x-www-form-urlencoded Use

for json string

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

table toolbar 1. First define the button in 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>
Copy after login

2. Reference in js

layui.use(&#39;table&#39;, function(){
    var table = layui.table;
    userPage.tab(&#39;/getUserList.action&#39;);
    //监听工具条
    table.on(&#39;tool(demo)&#39;, function(obj){
        var data = obj.data;
        userPage.data = obj.data;
        if(obj.event === &#39;detail&#39;){
            layer.msg(&#39;ID:&#39;+ data.id + &#39; 的查看操作&#39;);
        }
        else if(obj.event === &#39;del&#39;){
            layer.confirm(&#39;真的要删除这条记录么&#39;,{icon: 3, title:&#39;确定删除&#39;}, function(index){
                obj.del();
                $.post(&#39;/doDelete.action?id=&#39;+data.id,function (res) {
                    userPage.reload(res);
                });
                layer.close(index);
            });

        }
        else if(obj.event === &#39;add&#39;){
           layer.open({
               title:&#39;增加窗口&#39;,
               content:userPage.template,
               yes:function () {
                   var user = page.formToJson($(&#39;#layer_form&#39;).serialize());
                   var data = &#39;user=&#39;+user;
                  $.post(&#39;/doAdd.action&#39;,data,function (res) {
                      userPage.reload(res);
                  });
                  layer.closeAll();
               }
           })

        }
        else if(obj.event === &#39;edit&#39;){
            layer.open({
                title:&#39;编辑窗口&#39;,
                content:userPage.template,
                success:function () {
                    $(&#39;input[name="id"]&#39;).val(userPage.data.id);
                    $(&#39;input[name="username"]&#39;).val(userPage.data.username);
                    $(&#39;input[name="password"]&#39;).val(userPage.data.password);
                    $(&#39;input[name="gender"]&#39;).val(userPage.data.gender);
                    $(&#39;input[name="nichen"]&#39;).val(userPage.data.nichen);
                    $(&#39;input[name="birthday"]&#39;).val(userPage.data.birthday);
                },
                yes: function(){
                    var mgUser = page.formToJson($(&#39;#layer_form&#39;).serialize());
                    var data = &#39;user=&#39;+mgUser;
                    $.post(&#39;/doEdit.action&#39;,data,function (res) {
                        userPage.reload(res);
                    });
                    layer.closeAll();
                }
            })
        }
    });
});
Copy after login

2 .Server part

The Controller layer needs to receive the following parameters, page, limit, and conditions to be queried. The return value is based on the default return value given by the layui document

 @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;
    } 
Copy after login

The Service layer queries and Paging

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;
    } 
Copy after login

Note that since the Example generated by mybatis reverse engineering does not have limit and page, you need to add it yourself

    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;
    }
Copy after login

Then modify the mapper.xml of Mybatis and add the paging condition

<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>
Copy after login

This article is reproduced from: https://www.cnblogs.com/wangxiayun/p/9145638.html

For more informationlayuiPlease pay attention to the PHP Chinese websitelayui tutorialColumn

The above is the detailed content of Layui's method of implementing data tables and paging. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

What is the difference between layui and vue? What is the difference between layui and vue? Apr 04, 2024 am 03:54 AM

The difference between layui and Vue is mainly reflected in functions and concerns. Layui focuses on rapid development of UI elements and provides prefabricated components to simplify page construction; Vue is a full-stack framework that focuses on data binding, component development and state management, and is more suitable for building complex applications. Layui is easy to learn and suitable for quickly building pages; Vue has a steep learning curve but helps build scalable and easy-to-maintain applications. Depending on the project needs and developer skill level, the appropriate framework can be selected.

How layui implements self-adaptation How layui implements self-adaptation Apr 26, 2024 am 03:00 AM

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

How to transfer data in layui How to transfer data in layui Apr 26, 2024 am 03:39 AM

The method of using layui to transmit data is as follows: Use Ajax: Create the request object, set the request parameters (URL, method, data), and process the response. Use built-in methods: Simplify data transfer using built-in methods such as $.post, $.get, $.postJSON, or $.getJSON.

What does layui mean? What does layui mean? Apr 04, 2024 am 04:33 AM

layui is a front-end UI framework that provides a wealth of UI components, tools and functions to help developers quickly build modern, responsive and interactive web applications. Its features include: flexible and lightweight, modular design, rich components, Powerful tools and easy customization. It is widely used in the development of various web applications, including management systems, e-commerce platforms, content management systems, social networks and mobile applications.

What language is layui framework? What language is layui framework? Apr 04, 2024 am 04:39 AM

The layui framework is a JavaScript-based front-end framework that provides a set of easy-to-use UI components and tools to help developers quickly build responsive web applications. Its features include: modular, lightweight, responsive, and has complete documentation and community support. layui is widely used in the development of management backend systems, e-commerce websites, and mobile applications. The advantages are quick start-up, improved efficiency, and easy maintenance. The disadvantages are poor customization and slow technology updates.

The difference between layui framework and vue framework The difference between layui framework and vue framework Apr 26, 2024 am 01:27 AM

layui and vue are front-end frameworks. layui is a lightweight library that provides UI components and tools; vue is a comprehensive framework that provides UI components, state management, data binding, routing and other functions. layui is based on a modular architecture, and vue is based on a componentized architecture. layui has a smaller ecosystem, vue has a large and active ecosystem. The learning curve of layui is low, and the learning curve of vue is steep. Layui is suitable for small projects and rapid development of UI components, while vue is suitable for large projects and scenarios that require rich functions.

See all articles