JqueryGrid的例子使用

对于后台返回的时间类型的处理:comment.js有着较好的处理;http://cdn.staticfile.org/moment.js/2.24.0/moment.js

由于本人不想使用实体类返回数据,采用map,自然而然spring对实体类返回json的处理自然就不起效果了,sql中的时间类型就变得难处理起来。

本人先把sql中的时间类型变为java由js处理时间格式;

mybatis sql;

    <select id="getDynamicCitys" parameterType="map" resultMap="map">
        select <include refid="param"/>
        from city as c
        <where>
            <if test="id != null and id != '' ">
                c.ID LIKE concat(concat('%',#{id} ),'%')
            </if>
            <if test="name!=null and name !='' ">
                and  c.Name LIKE concat(concat('%',#{name} ),'%')
            </if>
            <if test="countryCode!=null and countryCode != '' ">
                and  c.CountryCode LIKE concat(concat('%',#{countryCode} ),'%')
            </if>
            <if test="district!=null and district != '' ">
                and  c.District LIKE concat(concat('%',#{district} ),'%')
            </if>
            <if test="population!=null and population != '' ">
                and  c.Population LIKE concat(concat('%',#{population} ),'%')
            </if>
        </where>
        order by ${sidx} ${sord}
    </select>

这样子返回的数据为:

数据传输结构:

即后台定义实体类:

页面处理 :jqGrid中cellModel

             {
                        name: 'birthday', index: 'birthday', width: 150, sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            console.log("cellvalue="+cellvalue);//单元格的数值
                            console.log("options="+JSON.stringify(options));//jqgrid这行配置的参数信息
                            console.log("rowObject="+JSON.stringify(rowObject));//一行的json数据
                            return (moment(rowObject.birthday).format("YYYY-MM-DD"));
                        }
                    },
                    {
                        name: 'createTime', index: 'createTime', width: 150, sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            return (moment(rowObject.createTime).format("YYYY-MM-DD HH:mm:ss"));
                        }
                    }

初始化参数:

url:获取数据的地址

dataType:  从服务器返回类型:json,xml,

mtype:ajax提交方式:post,get

colNames:列显示名称:是一个数组,

celModel:单元格属性配置:

pager:分页  ,分页id"#pager2"

viewrecords:定义是否显示总记录数:true

caption:表格名称

sortname:排序的字段.id之类的

sortorder:排序类型:desc,asc

表格自适应宽度和单元格填满表格

autowidth: true,//表格自适应宽度
shrinkToFit: true,//填满,

height:表格高度:150,一般不用

postData:ajax请求的参数:一般为模糊搜索,重载表格

rowList:数组用来调整表格显示的记录数[10,20,30],

rowNum:每页的个数,单页记录数,

rownumbers:true,//自动计算编号

caption:""//表格标题

gridComplete: function () {
    autoRNWidth("gridlist");//高度自适应么?
},

celModel常用参数:

align: 单元格对齐方式:  center, left ,right

name:表格列的名称:对应返回的json的key

hidden:是否隐藏此列

width:列的宽度:只能是像素:180,不能是百分比

label:列的名称:如果cellNames为空就会用此设置

key:true  即选择当前值为该tr 的id

sortable:是否可以排序,boolean

formatter:格式化单元格数据,formatter:function(cellValue,options,rowObject){}

本文所讲简单例子:如图:

后台控制层:

因为搜索是动态性的参数,即把request请求的参数都封装在map中,传入mybatis,看上面的sql;

   @RequestMapping(value = "/getCity")
    @ResponseBody
    public JqGridData getCity(HttpServletRequest request){
        System.out.println("-------------------------------");
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object>paramterNewMap=new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println(entry.getKey() + "-------------" + entry.getValue()[0]);
            paramterNewMap.put(entry.getKey(),entry.getValue()[0]);
        }
        Integer pageNum=Integer.parseInt(request.getParameter("page"));
        Integer pageSize=Integer.parseInt(request.getParameter("rows"));
        PageHelper.startPage(pageNum,pageSize);
//        List<Map<String, Object>> all = cityDao.getAll();
        List<Map<String, Object>> dynamicCitys = cityDao.getDynamicCitys(paramterNewMap);
        PageInfo info=new PageInfo(dynamicCitys);
        JqGridData data=new JqGridData();
        data.setRows(info.getList());
        data.setPage(info.getPageNum());
        data.setRecords(info.getTotal());
        data.setTotal(info.getPages());
        return data;
    }

这样子就达到了基本的显示功能,注意排序时候的参数:$和#的使用,如果用#,desc或者asc会被当成字符串,无法达到预期效果;

前端页面直接贴代码:

<%--
  Created by IntelliJ IDEA.
  User: lhl
  Date: 2019/12/27
  Time: 14:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="${pageContext.request.contextPath}/comment.jsp"/>
    <style>
        #search_list2 {
            display: none;
        }

        #myId {
            color: #1c94c4;
        }
    </style>
</head>
<body>
<div id="importExcel">
    <form action="/excelToSql" method="post" enctype="multipart/form-data" >
        <input type="file" id="excelFile" name="excelFile">
        <input type="submit">
    </form>
</div>
<form id="search_form">
    id:<input type="text" name="id">
    name:<input type="text" name="name">
    countryCode:<input type="text" name="countryCode">
    district:<input type="text" name="district">
    population:<input type="text" name="population">
</form>mytest1@139.196.125.230
<br>
<div>
    <button id="getRowData">获取选中行数据</button>
    <button id="delRowData">删除选中行</button>
    <button id="getNowPage">获取当前页</button>
    <button id="daoru">导入</button>
    <button id="daochu">导出</button>
    <button id="reload">重载表格</button>
    <button id="search">搜索</button>
    <button id="clear">清空</button>
    <br>
    <button id="getOneRow">获取选中的行的ID</button>
    <button id="hideNameColumn">隐藏name列</button>
    <button id="showNameColumn">显示name列</button>

    <button id="addOtherList">添加副表数据</button>
</div>

<table id="list2"></table>
<div id="pager2"></div>
<hr/>
<table id="otherList"></table>
<div id="otherListPage"></div>
<script>
    /**添加副表的数据
     */
    $("#addOtherList").click(function () {
        var selectId=jQuery("#list2").jqGrid('getGridParam', 'selarrrow');//获取选中行的ID
        if (selectId.length<=0){
            alert("请选择")
            return false;
        }
        var reccount = $("#otherList").getGridParam("reccount");
        for (var i=0;i<selectId.length;i++){
            var rowdata = $("#list2").jqGrid('getRowData', selectId[i]);//获取每一行的数据
            reccount+=1;
            $("#otherList").jqGrid('addRowData', reccount, {
                "id":rowdata['id'],
                "name":rowdata['name'],
                "countryCode":rowdata['countryCode'],
                "district":rowdata['district'],
                "population":rowdata['population'],
                "status":rowdata['status'],
                "sex":rowdata['sex'],
                "birthday":rowdata['birthday'],
                "birthday":rowdata['createTime']
            },"first");
        }
    });

    /**导出
     * */
    $("#daochu").click(function () {
        location.href="/getExportExcel";
    });
    /**导入
     * */
    $("#daoru").click(function () {
        $("#importExcel form").submit();
    });

    $(function () {
        pageInit();



    });


    function pageInit() {
        jQuery("#list2").jqGrid(
            {
                url: '/getCity',
                datatype: "json",
                colNames: ['id', 'name', 'countryCode', 'district', 'population', 'status', 'sex', 'birthday', 'createTime','operation'],
                colModel: [
                    {name: 'id', align: 'center', index: 'id', classes: 'myId', sortable: true},
                    {name: 'name', align: 'center',sortable: false, index: 'name'},
                    {name: 'countryCode', align: 'center',sortable: false, index: 'countryCode'},
                    {name: 'district', align: 'center', sortable: false,index: 'district'},
                    {name: 'population', align: 'center',sortable: false, index: 'population'},
                    {name: 'status', index: 'status',sortable: false, align: 'center'},
                    {name: 'sex', index: 'sex', align: 'center', sortable: false},
                    {
                        name: 'birthday', index: 'birthday', sortable: false, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            // console.log("cellvalue=" + cellvalue);//单元格的数值
                            // console.log("options=" + JSON.stringify(options));//jqgrid这行配置的参数信息
                            // console.log("rowObject=" + JSON.stringify(rowObject));//一行的json数据
                            return (moment(rowObject.birthday).format("YYYY-MM-DD"));
                        }
                    },
                    {
                        name: 'createTime', index: 'createTime', sortable: false, width: 200, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return (moment(rowObject.createTime).format("YYYY-MM-DD HH:mm:ss"));
                        }
                    },
                    {name: 'operate',align:'center',sortable: false,
                        formatter: function (cellvalue, options, rowObject) {
                            return '<a href="javascript:void(0);" style="color:#f60" οnclick="modify(\''+ rowObject.id+ '\');">查看</a>'+'&nbsp;&nbsp;<a href="javascript:void(0);" style="color:#f60" οnclick="modify(\''+ rowObject.id+ '\');">删除</a>';
                        }
                    }
                ],
                rowNum: 8,
                rowList: [10, 20, 30],
                pager: '#pager2',
                sortname: 'id',//初始化的时候排序字段
                mtype: "post",//提交的方式
                viewrecords: true,
                sortorder: "desc",//排序类型
                multiselect : true,//开启多选
                autowidth: true,
                shrinkToFit: true,
                height: 200,
                rownumbers: true,//自动计算编号
                caption: "JSON 实例",
                onSelectRow : function(ids) {
                    console.log(ids);//获取到的是这行的ID,然后再根据id获取其他的东西吧。
                    var select=jQuery("#list2").jqGrid('getRowData', ids);
                }
            });
        jQuery("#list2").jqGrid('navGrid', '#pager2', {edit: false, add: false, del: false});
        jQuery("#otherList").jqGrid(
            {
                url: '',
                datatype: "local",
                colNames: ['id', 'name', 'countryCode', 'district', 'population', 'status', 'sex', 'birthday', 'createTime'],
                colModel: [
                    {name: 'id', align: 'center', index: 'id', classes: 'myId', sortable: true},
                    {name: 'name', align: 'center',sortable: false, index: 'name'},
                    {name: 'countryCode', align: 'center',sortable: false, index: 'countryCode'},
                    {name: 'district', align: 'center', sortable: false,index: 'district'},
                    {name: 'population', align: 'center',sortable: false, index: 'population'},
                    {name: 'status', index: 'status',sortable: false, align: 'center'},
                    {name: 'sex', index: 'sex', align: 'center', sortable: false},
                    {
                        name: 'birthday', index: 'birthday', sortable: false, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return (moment(rowObject.birthday).format("YYYY-MM-DD"));
                        }
                    },
                    {
                        name: 'createTime', index: 'createTime', sortable: false, width: 200, align: 'center',
                        formatter: function (cellvalue, options, rowObject) {
                            return (moment(rowObject.createTime).format("YYYY-MM-DD HH:mm:ss"));
                        }
                    }
                ],
                rowNum: 8,
                rowList: [10, 20, 30],
                pager: '#otherListPage',
                sortname: 'id',//初始化的时候排序字段
                mtype: "post",//提交的方式
                viewrecords: true,
                sortorder: "desc",//排序类型
                // multiselect : true,//开启多选
                autowidth: true,
                shrinkToFit: true,
                height: 200,
                rownumbers: true,//自动计算编号
                caption: "JSON 实例",
                onSelectRow : function(ids) {
                    console.log(ids);//获取到的是这行的ID,然后再根据id获取其他的东西吧。
                    var select=jQuery("#list2").jqGrid('getRowData', ids);
                    console.log(select);
                }
            });



        jQuery("#otherList").jqGrid('navGrid', '#otherListPage', {edit: false, add: false, del: false});
        /**
         * 搜索时候重载表格数据
         */
        jQuery("#search").click(function() {
            $("#list2").jqGrid('setGridParam','postData', {
                q : 1,
                param1 : "p1"
            });
            $("#list2").trigger("reloadGrid");
        });
    }

    /**
     * 获取选中行的数据  ----一行
     */
    $("#getRowData").click(function () {
        var id = jQuery("#list2").jqGrid('getGridParam', 'selrow');
        if (id) {
            var ret = jQuery("#list2").jqGrid('getRowData', id);
            alert(JSON.stringify(ret))
        } else {
            alert("Please select row");
        }
    });

    /**
     * 多选框获取选中的ID   可以是一个或者多个
     */
    $("#getOneRow").click(function () {
        var s;
        s = jQuery("#list2").jqGrid('getGridParam', 'selarrrow');
        alert(s);
    })
    /**
     * 删除选中行
     * @type {jQuery|*}
     */
    $("#delRowData").click(function () {
        var id = jQuery("#list2").jqGrid('getGridParam', 'selrow');//获取选中的id
        if (id){
            var su=jQuery("#list2").jqGrid('delRowData', id);//true或者false
            if (su){
                alert("delete success")
            }else {
                alert("delete fail")
            }
        }else {
            alert("请选择一行数据!")
        }
    });


    /**
     * 获取当前页码
     */
    $("#getNowPage").click(function () {
        alert(jQuery('#list2').jqGrid('getGridParam','page'));
    })


    /**
     * 重载表格  自动回把当前页的页码传过去,
     */
    $("#reload").click(function () {
        $("#list2").jqGrid('setGridParam',{  // 重新加载数据
        }).trigger("reloadGrid");
    })


    /**
     * 搜索
     */
    $("#search").click(function () {
        var serialize = $("#search_form").serialize();
        $("#list2").jqGrid("setGridParam", {
            page:"1",
            postData: {
                "id":$("input[name='id']").val().trim(),
                "name":$("input[name='name']").val().trim(),
                "countryCode":$("input[name='countryCode']").val().trim(),
                "district":$("input[name='district']").val().trim(),
                "population":$("input[name='population']").val().trim()
            }//发送查询条件
        }).trigger("reloadGrid");//重新载入
    })

    /**
     * 清空form表单
     */
    $("#clear").click(function () {
        document.getElementById("search_form").reset();
    });


    /**
     * 隐藏name列
     */
    $("#hideNameColumn").click(function() {
        jQuery("#list2").jqGrid( 'hideCol', "name");
    });
    /**
     * 显示name列
     */
    $("#showNameColumn").click(function() {
        jQuery("#list2").jqGrid( 'showCol', "name");
    });

</script>
</body>
</html>

新增主从副表;

主从副表效果如图;特别注意:未写去重操作,可以两个for循环进行校验重复,禁止添加已添加数据

多级表格:

subGrid : true,//开启多级表格
subGridUrl : '/getSubCity',//多级表格请求路径
subGridModel : [ {
    name : [ 'id', 'name', 'countryCode', 'district', 'population'],
    width : [ 55, 200, 80, 80, 80 ]
} ],

返回参数类型为json格式的数据,不再是之前有分页格式的data数据类型;

多级表格接收的参数:

 按照类型,自定义返回数据结构;当然你也可以写个试题类。

  /**
     * 多级表格数据返回结构
     * 比如表格返回的详情表格
     * @param list
     * @return
     */
    public static Map<String,Object> getJsonReaderData(List<Map<String, Object>>list){
        Map<String,Object>map=new HashMap<>();
        map.put("page","1");
        map.put("total","1");
        map.put("records",list.size());
        List<Map<String,Object>>mapList=new ArrayList<>();
        list.forEach(t->{
            Map<String,Object>contentMap=new HashMap<>();
            contentMap.put("id",t.get("id"));//每行的id
//选取你前端表格中需要显示的属性字段数据,和subGridModel中name中属性应一致
//            'id', 'name', 'countryCode', 'district', 'population'
            List<Object>a=new ArrayList<>();
            a.add(t.get("id"));
            a.add(t.get("name"));
            a.add(t.get("countryCode"));
            a.add(t.get("district"));
            a.add(t.get("population"));
            contentMap.put("cell",a);//内容放数组汇总
            mapList.add(contentMap);
        });
        map.put("rows",mapList);
        return map;
    }

控制层请求访问:只limit了四个数据进行测试

        List<Map<String, Object>> all = cityDao.getLimit();
        Map<String, Object> map = JqGridData.getJsonReaderData(all);
        return map;

测试效果如下:

至此:jqGrid的基本功能就完成了,其他的复杂的请查看官网;

如有不解,请加java爱好群大家交流:852665736;大家一起交流,一同进步

无偿免费分享源码以及技术和面试文档,更多优秀精致的源码技术栈分享请关注微信公众号:gh_817962068649 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值