java web 学习Java相关java web

easyUI treeGrid异步加载,前端+后台实现,包括增删

2016-08-02  本文已影响1868人  hwj3747

作者:hwj3747
转载请注明

说明

前端使用的是easyUI 1.3.6+jq
后台使用的是springMVC
初始化调用后台getCourse方法,返回的json数据格式如下:

{"total":3,"rows":[
    {"id":1,"typeName":"All Tasks","description":"3/4/2010","sort":"3/20/2010"},
    {"id":2,"typeName":"All Tasks","description":"3/4/2010","sort":"3/20/2010","_parentId":1},
        {"id":3,"typeName":"All Tasks","description":"3/4/2010","sort":"3/20/2010","_parentId":2}]
    }

保存一行数据,用js取得row的数据,再转化为json,调用saveCourseType传到后台。
删除一行,取得行id,调用deleteCourseType删除数据。

前端代码

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>CheckBox Tree - jQuery EasyUI Demo</title>
    <link rel="stylesheet" type="text/css" href="<%=contextPath%>/js/easyui-1.3.6/themes/metro-blue/easyui.css">
    <link rel="stylesheet" type="text/css" href="<%=contextPath%>/js/easyui-1.3.6/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="<%=contextPath%>/js/css/demo.css">
    <script type="text/javascript" src="<%=contextPath%>/js/easyui-1.3.6/jquery.min.js"></script>
    <script type="text/javascript" src="<%=contextPath%>/js/easyui-1.3.6/jquery.easyui.min.js"></script>

<title>可编辑的表格树</title>
</head>
//菜单栏
<div data-options="region:'north',title:''"
        style="height: 25px; padding: 5px;">
        <a href="#" class="easyui-linkbutton"
            data-options="iconCls:'icon-edit'" onclick="beginEdit()">编辑</a> <a
            href="#" class="easyui-linkbutton" data-options="iconCls:'icon-save'"
            onclick="saveEdit()">保存编辑</a> <a href="#" class="easyui-linkbutton"
            data-options="iconCls:'icon-add'" onclick="appendRoot()">新增根目录</a> <a
            href="#" class="easyui-linkbutton" data-options="iconCls:'icon-add'"
            onclick="append()">新增目录</a> <a href="#" class="easyui-linkbutton"
            data-options="iconCls:'icon-cancel'" onclick="removeIt()">删除</a>
    </div>

//treegrid主表
    <table id="tg" class="easyui-treegrid" title="课程分类编辑"
        style="width: 900px; height: 600px"
        data-options="
                iconCls: 'icon-ok',
                rownumbers: true,
                animate: true,
                fitColumns: true,
                url: '<%=contextPath%>/courseType/getCourseType',
                method: 'get',
                idField: 'id',
                treeField: 'typeName',
                onBeforeExpand:function(row){  
                    $('#tg').treegrid('options').url = '<%=contextPath%>/courseType/getCourseType?parentId='+row.id;               
                },
                onContextMenu: onContextMenu
                                
            ">
        <thead>
            <tr>
                <th data-options="field:'typeName',width:70,editor:'text'">名称</th>
                <th data-options="field:'description',width:50,editor:'text'">描述</th>
                <th data-options="field:'sort',width:20,editor:'text'">排序</th>
            </tr>
        </thead>
    </table>

//右键菜单选项
    <div id="mm" class="easyui-menu" style="width: 120px;">
        <div onclick="append()" data-options="iconCls:'icon-add'">新增</div>
        <div onclick="removeIt()" data-options="iconCls:'icon-remove'">删除</div>
        <div class="menu-sep"></div>
        <div onclick="collapse()">收起</div>
        <div onclick="expand()">展开</div>
    </div>

JS代码

<script type="text/javascript">
    //treegrid 的js代码
    //编辑目录
    var editingId=null; 
    function ff(row) {
        $('#tg').treegrid('options').url ='<%=contextPath%>/courseType/getCourseType?parentId='+row.id;
    }
    function formatProgress(value) {
        if (value) {
            var s = '<div style="width:100%;border:1px solid #ccc">'
                    + '<div style="width:' + value
                    + '%;background:#cc0000;color:#fff">' + value + '%' + '</div>'
            '</div>';
            return s;
        } else {
            return '';
        }
    }
    function onContextMenu(e, row) {
        if (row) {
            e.preventDefault();
            $(this).treegrid('select', row.id);
            $('#mm').menu('show', {
                left : e.pageX,
                top : e.pageY
            });
        }
    }
//生成节点ID
    function uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "";

        var uuid = s.join("");
        return uuid;
        }


//添加节点
    function append() {
        if (editingId != null){
            $.messager.alert("提示信息", "请先保存");
            return;
        }
        var uid=uuid();
        var node = $('#tg').treegrid('getSelected');
        expand();
        var parentId;
        if(node) parentId=node.id;
        else parentId=null;
        $('#tg').treegrid('append', {
            parent : parentId,
            data : [ {
                id : uid,
                typeName : '',
                sort :'1'
            } ]
        })

        editingId=uid;
        if (editingId != null){
            $('#tg').treegrid('select', editingId);
        }
        $('#tg').treegrid('beginEdit', editingId);
    }

//添加跟节点
    function appendRoot() {
        if (editingId != null){
            $.messager.alert("提示信息", "请先保存");
            return;
        }
        var uid=uuid();
        var node = $('#tg').treegrid('getSelected');
        expand();
        $('#tg').treegrid('append', {
            parent : null,
            data : [ {
                id : uid,
                typeName : '',
                sort :'1'
            } ]
        })
        editingId=uid;
        if (editingId != null){
            $('#tg').treegrid('select', editingId);
        }
        $('#tg').treegrid('beginEdit', editingId);
    }
//移除节点
    function removeIt() {
        if (editingId != null){
            $.messager.alert("提示信息", "请先保存");
            return;
        }
        var node = $('#tg').treegrid('getSelected');
        if (node==null)
            $.messager.alert("提示信息", "请选择一个节点");
        if (node) {
            var dataObj = {};
            ajaxCall("get", contextPath+'/courseType/deleteCourseType?id='+node.id, dataObj, function(XMLHttpRequest,
                    data) {
                $.messager.alert("提示信息", "删除成功");
            }, function(XMLHttpRequest) {
            });
            $('#tg').treegrid('remove', node.id);
        }
    }
    function collapse() {
        var node = $('#tg').treegrid('getSelected');
        if (node) {
            $('#tg').treegrid('collapse', node.id);
        }
    }
//展开节点
    function expand() {
        var node = $('#tg').treegrid('getSelected');
        if (node) {
            $('#tg').treegrid('expand', node.id);
        }
    }

//开始编辑
    function beginEdit(){
        if (editingId != null){
            $('#tg').treegrid('cancelEdit', editingId);
            $('#tg').treegrid('select', editingId);
            editingId = null;
            return;
        }
        var row = $('#tg').treegrid('getSelected');
        if (row){
            editingId = row.id
            $('#tg').treegrid('beginEdit', editingId);
        }
    }
//保存编辑
    function saveEdit(){
        if (editingId != null){
            var t = $('#tg');
            t.treegrid('endEdit', editingId);
            $('#tg').treegrid('select', editingId);
            var row = $('#tg').treegrid('getSelected');
            var dataObj = {};
            dataObj.rows = JSON.stringify(row);
            ajaxCall("post", contextPath+'/courseType/saveCourseType', dataObj, function(XMLHttpRequest,
                    data) {
                $.messager.alert("提示信息", "保存成功");
            }, function(XMLHttpRequest) {
            });
            editingId = null;
        }
    }
    </script>

后台java代码

//获取treegrid列表
@RequestMapping(value = "/getCourseType")
    public @ResponseBody Map<String,Object> tree_data(HttpServletRequest request) throws Exception {
        
        String parentId = ConvertUtils.cStr(request.getParameter("parentId"));
        Map<String, Object>  param = new HashMap<String,Object>();
        List<CourseType> courseTypes = new ArrayList<CourseType>();
        
        if(StringUtils.isNotEmpty(parentId)){
            courseTypes = courseTypeService.queryTree(null, parentId,null);
        } else {
            courseTypes = courseTypeService.queryTree(null, null,"1");
        }
        List<Map<String,Object>> dateList = new ArrayList<Map<String,Object>>();
        if(courseTypes.size()>0){
            Map<String,Object> map = null;
            Map<String, Object>  params = new HashMap<String,Object>();
            for(CourseType courseType:courseTypes){
                map = new HashMap<String,Object>();
                map.put("id", courseType.getId());
                map.put("typeName", courseType.getTypeName());
                map.put("sort", courseType.getSort());
                map.put("description", courseType.getDescription());    
                
                
                if(StringUtils.isEmpty(courseType.getParentId())){
                    map.put("_parentId", null);
                }
                else{
                    map.put("_parentId", courseType.getParentId());
                }
                
                //根据id判断是否有子节点
                params.put("parentId", courseType.getId());
                int count = courseTypeService.querySelectRowCount(params);
                if(count>0){
                    map.put("state", "closed");
                }
                dateList.add(map);
            }
        }
        param.put("rows", dateList);
        return param;
    }
//保存treegrid的某一列
    @RequestMapping(value = "/saveCourseType", method = RequestMethod.POST)
    public @ResponseBody int saveDirectory(HttpServletRequest request) throws Exception {
        Map<String, Object> params = CommonUtil.getNewSqlMap();
        String rows = ConvertUtils.cStr(request.getParameter("rows"));
        Map<String,String> map=JsonParser.parseJsonStrNull(rows);
        params.put("id",map.get("id"));
        params.put("typeName",map.get("typeName"));
        params.put("description", map.get("description"));
        params.put("parentId", map.get("_parentId"));
        params.put("sort", map.get("sort"));
        params.put("delFlag", 0);
        String parentIds=map.get("_parentId")+",";
        String parentId=map.get("_parentId");
        while(true){
            parentId=courseTypeService.findParentId(parentId);
            if(StringUtils.isEmpty(parentId)){
                break;
            }
            parentIds=parentIds+parentId+",";
        }
        params.put("parentIds", parentIds);
        if(courseTypeService.updateObject(params)==0){
            courseTypeService.saveObject(params);
        }
        return 1;
    }
    //删除某一行
    @RequestMapping(value = "/deleteCourseType")
    public @ResponseBody Map<String, Object> deleteDirectory(HttpServletRequest request) throws Exception {
        String id=ConvertUtils.cStr(request.getParameter("id"));
        Map<String,Object> result = new HashMap<String, Object>();
        Map<String, Object> params = CommonUtil.getNewSqlMap();
        params.put("id",id);
        courseTypeService.deleteObject(params); 
        return result;
    }

注意事项

1.后台传回的json数据的key,必须与前端treegrid的表头name相对应。
2.要使用编辑功能,前端表头必须加入editor:'text'参数,具体类型参见官方文档。
3.后台传回的参数如果包含state参数,state为closed代表该节点具有子节点。
4.后台传回的json数据必须有一个以上是不包含_parentId字段的,也就是必须要有父节点,否则无法显示。

上一篇下一篇

猜你喜欢

热点阅读