使用LayUI操作数据表格

接着 上一篇 继续完善我们的demo,这次我们加一个搜索按钮

搜索

源代码地址 点我

table标签的上方,加入这样一组html

 

<div class="demoTable">
    搜索商户:
    <div class="layui-inline">
        <input class="layui-input" name="keyword" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" data-type="reload">搜索</button>
</div>

 

js加入初始化代码和定义加载方法

layui.use('table', function(){
    var table = layui.table;

    //方法级渲染
    table.render({
        elem: '#LAY_table_user'
        ,url: 'UVServlet'
        ,cols: [[
            {checkbox: true, fixed: true}
            ,{field:'id', title: 'ID', width:80, sort: true, fixed: true}
            ,{field:'aid', title: '商户', width:80, sort: true}
            ,{field:'uv', title: '访问量', width:80, sort: true,edit:true}
            ,{field:'date', title: '日期', width:180}
            ,{field:'datatype', title: '日期类型', width:100}

        ]]
        ,id: 'testReload'
        ,page: true
        ,height: 600
    });

    var $ = layui.$, active = {
        reload: function(){
            var demoReload = $('#demoReload');

            table.reload('testReload', {
                where: {
                    keyword: demoReload.val()
                }
            });
        }
    };
)};

 

绑定click点击事件

$('.demoTable .layui-btn').on('click', function(){
    var type = $(this).data('type');
    active[type] ? active[type].call(this) : '';
});

此时点击查询按钮,会将keyword这个关键字传到后端,接下来就是自己处理查询关键字业务了。

到目前为止,搜索也有了,分页也有了,对了,分页会自动传到后端page,limit2个值到后台,相当于(pageindex,pagesize

预览下效果

看看请求的参数

 

 从参数可以看出,数据表格默认是get请求,返回的数据结构是这样的 

关于数据表格绑定数据和请求就讲到这里,如果需要了解更多,在我上一篇里面有,这里就不展开了

给表格增加操作按钮

首先加入一组html,放到table标签下面,代码如下

<table class="layui-hide" id="LAY_table_user" lay-filter="useruv"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-mini" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>
</script>

然后在js中指定工具条

 //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            ,url: 'UVServlet'
            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field:'id', title: 'ID', width:80, sort: true, fixed: true}
                ,{field:'aid', title: '商户', width:80, sort: true}
                ,{field:'uv', title: '访问量', width:80, sort: true,edit:true}
                ,{field:'date', title: '日期', width:180}
                ,{field:'datatype', title: '日期类型', width:100}
                ,{field:'right', title: '操作', width:177,toolbar:"#barDemo"}
            ]]
            ,id: 'testReload'
            ,page: true
            ,height: 600
        });

界面效果如下

 

 接下来需要给按钮绑定事件,来完成功能操作

LayUI里面,一般采用table.on()来表示事件,例如这个

 

//监听表格复选框选择
        table.on('checkbox(useruv)', function(obj){
            console.log(obj)
        });

 

我勾选一个复选框,就打印一个日志

 

加入以下js代码,来绑定工具条事件

//监听工具条
  table.on('tool(demo)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){
      layer.msg('ID:'+ data.id + ' 的查看操作');
    } else if(obj.event === 'del'){
      layer.confirm('真的删除行么', function(index){
        obj.del();
        layer.close(index);
      });
    } else if(obj.event === 'edit'){
      layer.alert('编辑行:<br>'+ JSON.stringify(data))
    }
  });

这时候,点击按钮就会有反应了。这里说明一下

 

接下来就是把数据传递到后端,直接将js改造如下

 

//监听工具条
table.on('tool(useruv)', function(obj){
    var data = obj.data;
    if(obj.event === 'detail'){
        layer.msg('ID:'+ data.id + ' 的查看操作');
    } else if(obj.event === 'del'){
        layer.confirm('真的删除行么', function(index){
            console.log(data);
            $.ajax({
                url: "UVServlet",
                type: "POST",
                data:{"uvid":data.id,"memthodname":"deleteuv","aid":data.aid},
                dataType: "json",
                success: function(data){

                    if(data.state==1){
                       //删除这一行
                        obj.del();
                       //关闭弹框
                        layer.close(index);
                        layer.msg("删除成功", {icon: 6});
                    }else{
                        layer.msg("删除失败", {icon: 5});
                    }
                }

            });
        });
    } else if(obj.event === 'edit'){

        layer.prompt({
            formType: 2
            ,title: '修改 ID 为 ['+ data.id +'] 的访问量'
            ,value: data.uv
        }, function(value, index){
         //这里一般是发送修改的Ajax请求
            EidtUv(data,value,index,obj);
            


        });



    }
});

编辑的方法
function  EidtUv(data,value,index,obj) {
    $.ajax({
        url: "UVServlet",
        type: "POST",
        data:{"uvid":data.id,"memthodname":"edituv","aid":data.aid,"uv":value},
        dataType: "json",
        success: function(data){

            if(data.state==1){
               //关闭弹框
                layer.close(index);
                //同步更新表格和缓存对应的值
                obj.update({
                    uv: value
                });
                layer.msg("修改成功", {icon: 6});
            }else{
                layer.msg("修改失败", {icon: 5});
            }
        }

    });
}
View Code

 

 

预览效果

 

至此,数据表格的绑定、展示、分页、搜索、查看、编辑、删除、排序 功能都已经完成,是不是很简单?

此处粘贴出完整的页面代码

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

    <link rel="stylesheet" href="../Assets/css/layui.css">


    <!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<div style="margin-bottom: 5px;">

    <!-- 示例-970 -->
    <ins class="adsbygoogle" style="display:inline-block;width:700px;height:700px" data-ad-client="ca-pub-6111334333458862" data-ad-slot="3820120620"></ins>

</div>
<div class="demoTable">
    搜索商户:
    <div class="layui-inline">
        <input class="layui-input" name="keyword" id="demoReload" autocomplete="off">
    </div>
    <button class="layui-btn" data-type="reload">搜索</button>
</div>

<table class="layui-hide" id="LAY_table_user" lay-filter="useruv"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary layui-btn-mini" lay-event="detail">查看</a>
    <a class="layui-btn layui-btn-mini" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-mini" lay-event="del">删除</a>
</script>


<script src="../Assets/layui.js"></script>
<script>
    layui.use('table', function(){
        var table = layui.table;

        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            ,url: 'UVServlet'
            ,cols: [[
                {checkbox: true, fixed: true}
                ,{field:'id', title: 'ID', width:80, sort: true, fixed: true}
                ,{field:'aid', title: '商户', width:80, sort: true}
                ,{field:'uv', title: '访问量', width:80, sort: true,edit:true}
                ,{field:'date', title: '日期', width:180}
                ,{field:'datatype', title: '日期类型', width:100}
                ,{field:'right', title: '操作', width:177,toolbar:"#barDemo"}
            ]]
            ,id: 'testReload'
            ,page: true
            ,height: 600
        });

        var $ = layui.$, active = {
            reload: function(){
                var demoReload = $('#demoReload');

                table.reload('testReload', {
                    where: {
                        keyword: demoReload.val()
                    }
                });
            }
        };



        //监听表格复选框选择
        table.on('checkbox(useruv)', function(obj){
            console.log(obj)
        });
        //监听工具条
        table.on('tool(useruv)', function(obj){
            var data = obj.data;
            if(obj.event === 'detail'){
                layer.msg('ID:'+ data.id + ' 的查看操作');
            } else if(obj.event === 'del'){
                layer.confirm('真的删除行么', function(index){
                    console.log(data);
                    $.ajax({
                        url: "UVServlet",
                        type: "POST",
                        data:{"uvid":data.id,"memthodname":"deleteuv","aid":data.aid},
                        dataType: "json",
                        success: function(data){

                            if(data.state==1){
                                obj.del();
                                layer.close(index);
                                layer.msg("删除成功", {icon: 6});
                            }else{
                                layer.msg("删除失败", {icon: 5});
                            }
                        }

                    });
                });
            } else if(obj.event === 'edit'){

                layer.prompt({
                    formType: 2
                    ,title: '修改 ID 为 ['+ data.id +'] 的访问量'
                    ,value: data.uv
                }, function(value, index){
                    EidtUv(data,value,index,obj);
                   


                });



            }
        });

        $('.demoTable .layui-btn').on('click', function(){
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        function  EidtUv(data,value,index,obj) {
            $.ajax({
                url: "UVServlet",
                type: "POST",
                data:{"uvid":data.id,"memthodname":"edituv","aid":data.aid,"uv":value},
                dataType: "json",
                success: function(data){

                    if(data.state==1){

                        layer.close(index);
                        //同步更新表格和缓存对应的值
                        obj.update({
                            uv: value
                        });
                        layer.msg("修改成功", {icon: 6});
                    }else{
                        layer.msg("修改失败", {icon: 5});
                    }
                }

            });
        }


    });
</script>
</body>
</html>
View Code

 

 应大家要求,将servlet代码贴出来,其中用到了json.jar

import com.weimob.models.Pagination;
import com.weimob.models.QueryResult;
import com.weimob.models.UvData;
import com.weimob.uv.dao.WeiMobUvDao;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@WebServlet(name="UVServlet",
        urlPatterns={"/WebApp/UVServlet"},
        loadOnStartup=0)
public class UVServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String memthodname = request.getParameter("memthodname");
        if(memthodname!=null){
            switch (memthodname){
                case "queryList":
                    break;
                case "deleteuv":
                    deleteUv(request,response);
                    break;
                case "edituv":
                    edituv(request,response);
                    break;
                default:
                    queryList(request, response);
            }

        }else {
            queryList(request, response);

        }


    }

    private void queryList(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {


        String str = request.getParameter("keyword");
        String pindex = request.getParameter("page");
        String limit = request.getParameter("limit");
        response.setStatus(200);
        int aid = 0;
        int pagesize=15;
        int index = 0;
        int total = 0;
        if (str != null && str.length() > 0) {
            aid = Integer.valueOf(str);

        }
        if (pindex != null) {
            index = Integer.parseInt(pindex);
            pagesize=Integer.parseInt(limit);
        }


        WeiMobUvDao dao = new WeiMobUvDao();

        StringBuffer sbtotal = new StringBuffer();
        sbtotal.append("SELECT count(1) as count FROM WpMulShopDataUv_1 ");
        if (aid > 0) {
            sbtotal.append(" where aid=");
            sbtotal.append(aid);

        }
        total = dao.GetCount(sbtotal.toString());
        if (total > 0) {

            StringBuffer sb = new StringBuffer();
            sb.append("SELECT Id,AId,Uv,DataType,Date FROM WpMulShopDataUv_1 ");
            if (aid > 0) {
                sb.append(" where aid=");
                sb.append(aid);

            }
            if (total > pagesize) {
                sb.append(" Limit ");
                int start = (index - 1) * pagesize;
                if (start < 0) {
                    start = 0;

                }
                sb.append(start);
                sb.append(",");
                sb.append(pagesize);
            }

            List<UvData> list = dao.QueryUv(sb.toString());

            QueryResult<UvData> result = new QueryResult<UvData>(total, list);

            String jsonstr= ConvertListToPageJson(list,total);
            System.out.println(jsonstr);
           request.setAttribute("result", jsonstr);
            response.getWriter().print(jsonstr);

        }else {
            QueryResult<UvData> result = new QueryResult<UvData>(total, null);
            JSONObject obj = new JSONObject(result);
            response.getWriter().print(obj);

        }





}

    private void deleteUv(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {


        String str = request.getParameter("aid");
        String uvid = request.getParameter("uvid");
        String limit = request.getParameter("limit");
        response.setStatus(200);
        int aid = 0;
        int uv_id=0;
        int index = 0;
        int total = 0;
        if (str != null && str.length() > 0) {
            aid = Integer.valueOf(str);

        }
        if (uvid != null) {
            uv_id = Integer.parseInt(uvid);
        }
       if(uv_id<=0){
           response.getWriter().print("参数无效");
       }

        WeiMobUvDao dao = new WeiMobUvDao();

        List list=new ArrayList<Integer>();
        list.add(uv_id);
        int res_count= dao.DeleteByIds(aid,list);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state",res_count>0?true:false);
        jsonObject.put("code",0);
        jsonObject.put("msg","null");
        response.getWriter().print(jsonObject);







    }

    private void edituv(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {


        String str = request.getParameter("aid");
        String uvid = request.getParameter("uvid");
        String uvstr = request.getParameter("uv");
        response.setStatus(200);
        JSONObject jsonObject = new JSONObject();
        int aid = 0;
        int uv_id=0;
        int uv = 0;
        if (str != null && str.length() > 0) {
            aid = Integer.valueOf(str);

        }
        if (uvid != null) {
            uv_id = Integer.parseInt(uvid);
            uv= Integer.parseInt(uvstr);
        }
        if(uv_id<=0){
            response.setStatus(500);
            jsonObject.put("state",-1);
            jsonObject.put("msg","参数无效");
            response.getWriter().print(jsonObject);

        }
        if(uv<0){
            response.setStatus(500);
            jsonObject.put("state",-1);
            jsonObject.put("msg","参数无效");
            response.getWriter().print(jsonObject);
        }
        WeiMobUvDao dao = new WeiMobUvDao();

        List list=new ArrayList<Integer>();
        list.add(uv_id);
        UvData res= dao.getByIds(aid,uv_id);
        if(res==null){
            response.setStatus(500);
            jsonObject.put("state",-1);
            jsonObject.put("msg","参数无效,对象不存在");
            response.getWriter().print(jsonObject);
            return;
        }
         int res_count= dao.modifyEntity(res);

        jsonObject.put("state",res_count>0?true:false);
        jsonObject.put("code",0);
        jsonObject.put("msg","null");
        response.getWriter().print(jsonObject);
    }
    public  String ConvertListToPageJson(List<?> list, int countList) {
        // 新建一个json数组
        JSONArray jsonArray = new JSONArray();
        // 新建一个json对象
        JSONObject jsonObject = null;
        // 遍历泛型集合
        for (Object object : list) {
            jsonObject = new JSONObject(object);
            jsonArray.put(jsonObject);
        }
        // 转换数据格式
        String json = jsonArray.toString();
        // 拼接字符串
        StringBuffer sb = new StringBuffer();
        sb.append("{\"count\":");
        sb.append(countList);
        sb.append(",\"code\":");
        sb.append(0);
        sb.append(",\"msg\":");
        sb.append("null");
        sb.append(",\"data\":");
        sb.append(json);
        sb.append("}");
        String jsonString = sb.toString();
        return jsonString;
    }
}
View Code

 

 

 

package com.example.demo.data.models;

import com.alibaba.fastjson.annotation.JSONField;

public class Uv {
    private int id;
    @JSONField(name="aid")
    public long getaId() {
        return aId;
    }

    public void setAId(long aId) {
        this.aId = aId;
    }

    private long aId;
    @JSONField(name="shopid")
    public long getShopId() {
        return shopId;
    }

    public void setShopId(long shopId) {
        this.shopId = shopId;
    }

    private long shopId;
    @JSONField(name="date")
    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    private String date;
    @JSONField(name="uv")
    public int getUv() {
        return uv;
    }

    public void setUv(int uv) {
        this.uv = uv;
    }

    private int uv;
    @JSONField(name="id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    @JSONField(name="datetype")
    public String getDataType() {
        return dataType;
    }

    public void setDataType(String dataType) {
        this.dataType = dataType;
    }

    private String dataType;
}

 

  

静态文件下载地址

不少同学不知道怎么绑定数据源,欢迎看我上一篇。表格数据源格式:http://www.layui.com/demo/table/user/?page=1&limit=30

总结:

LayUI为我们提供了强大丰富的类库组件,完善的文档,学习成本和开发成本相对低廉,具有快速,扁平化等优点。

关于数据表格的介绍就到这里。官方文档

源代码地址 点我 

应不少同学的要求,因为时间久远项目早就没了,最近花了点时间重新写了个demo,demo验证过 可以正常使用

posted @ 2017-10-02 14:14  井传红  阅读(244482)  评论(47编辑  收藏  举报