Layui之异步加载树

需求

        将用户角色与组织机构下的人员进行绑定。组织机构下面有很多人,数据量很大,导致整颗书的数据加载不出来,故需要点击组织机构数的节点,来查询该组织机构下的人员进行显示,进而选择人员进行绑定。效果图如下:

Layui之异步加载树_第1张图片

Layui之异步加载树_第2张图片

       参考博客:https://blog.csdn.net/u010951692/article/details/51833077

 

           查看了很多博客,也遇到了很多坑,这里,记录一下。

 

jsp:

       表格:

       barTool的按钮:

JS:

      表格加载:

//表格加载
layui.use('table', function () {
    var table = layui.table;
    table.render({
        elem: '#roleTable'
        , id: 'idRole'
        , url: basePathUrl + '/role/queryRole/' + companyId
        , cols: [[
              {type: 'numbers'}
            , {checkbox: true}
            , {field: 'id', width: 250, title: '角色编码', sort: true}
            , {field: 'roleName', width: 150, title: '角色名称', sort: true, align: 'left'}
            , {field: 'roleType', width: 100, title: '角色类型', sort: true, align: 'left'}
            , {field: 'roleDescribe', width: 220, title: '角色描述', align: 'center'}
            , {field:'isBuiltIn',width:100,title:'是否可编辑',align:'center'}
            , {field: 'right', title: '操作', width: 145, toolbar: "#barTool", align: 'center'}     ①:这里是嵌入了一个barTool按钮
        ]]
        , page: true
        , height: 'full-60'
    });
    table.on('tool(roleuv)', function (obj) {       ②:这里来监控这些toolbar的点击事件。
        $('#treeApplication').attr("disabled", false);
        var data = obj.data;
        window.mydata=data;
        console.log(window.mydata+"11");
        console.log(data);
        if (obj.event === 'chooseApp') {         ③:这里对应的是分配资源的按钮
            var setting = {
                async: {
                    enable: true,
                    type: "get",
                    url: basePathUrl + "/companyApplication/queryCompanyAppTree/" + companyId + "/" + data.id
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "ps", "N": "s"},
                    radioType: "all"
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                }
            };
            zTreeObjApp = $.fn.zTree.init($("#treeApplication"), setting);
            layer.open({
                type: 1
                , title: '分配资源'
                , maxmin: true
                , area: ['450px', '500px']
                , shade: 0
                , content: $('#treeApplication')
                , btn: ['取消', '保存']
                , yes: function () {
                    layer.closeAll();
                }
                , btn2: function () {
                    var treeObj = $.fn.zTree.getZTreeObj("treeApplication");
                    var nodes = treeObj.getChangeCheckedNodes();
                    if (nodes.length < 1) {
                        layer.msg('请编辑要给该角色分配的资源!', {icon: 7});
                        return;
                    }
                    $.ajax({
                        url: basePathUrl + "/roleApplication/saveRoleApplication/" + data.id,
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json;charse=UTF-8",
                        headers: {'Authorization': token},
                        data: JSON.stringify(nodes),
                        success: function (result) {
                            if (result.code === "200") {
                                layer.msg("保存资源成功!", {icon: 6});
                            }
                        },
                        error: function () {
                            layer.msg("保存资源失败!", {icon: 5})
                        }
                    })
                }
            });
        } else if (obj.event === 'detail') {        ④:这里就是今天要梳理的“组织”对应的数,来实现异步加载。
            $('#app')[0].reset()
            $('#app').attr("disabled", false);
            layer.open({
                type: 1
                , title: '绑定组织机构(请务必绑定到具体个人,否则绑定失效)'
                , maxmin: true
                , area: ['450px', '500px']
                , shade: 0
                , content: $('#app')
            });

            // ztree加载======================异步加载的这颗树================
            var zTreeObj;

            var setting = {
                async: {
                    enable: true,
                    type: "get",    //下面加载的这个url就是初始化树的接口,根据公司ID查询该公司的组织机构。
                    url: basePathUrl + "/organization/queryOrganizationUserTree?companyId="+companyId,   
                   // otherParam: ["companyId", companyId],
                    autoParam:["id"]   //这个id对应着点击某一个组织机构后,将点击的节点ID传到接口的ID,会自动获取点击ID,对应异步查询的接口
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    //radioType: "level"
                   chkboxType: {"Y": "s", "N": "s"},   //这里是节点的父子关联设置。
                    radioType: "all"
                },
                callback : {
                   // beforeAsync  : ztreeBeforeAsync,
                    onClick:ztreeOnAsyncSuccess,    //点击树节点出发的事件,也就是异步加载的接口(参数在上面的autoParam)
                    onAsyncSuccess : ztreeOnAsyncSuccess, //这个也要添加

                }
            };
            //初始化树============================================
            zTreeObj = $.fn.zTree.init($("#bindOrganization"), setting);  //注意,初始化树的时候,要加  # 号(获取的时候,不能加#,具体见下方)
        }

    })
});①:这里是嵌入了一个barTool按钮
        ]]
        , page: true
        , height: 'full-60'
    });
    table.on('tool(roleuv)', function (obj) {       ②:这里来监控这些toolbar的点击事件。
        $('#treeApplication').attr("disabled", false);
        var data = obj.data;
        window.mydata=data;
        console.log(window.mydata+"11");
        console.log(data);
        if (obj.event === 'chooseApp') {         ③:这里对应的是分配资源的按钮
            var setting = {
                async: {
                    enable: true,
                    type: "get",
                    url: basePathUrl + "/companyApplication/queryCompanyAppTree/" + companyId + "/" + data.id
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "ps", "N": "s"},
                    radioType: "all"
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                }
            };
            zTreeObjApp = $.fn.zTree.init($("#treeApplication"), setting);
            layer.open({
                type: 1
                , title: '分配资源'
                , maxmin: true
                , area: ['450px', '500px']
                , shade: 0
                , content: $('#treeApplication')
                , btn: ['取消', '保存']
                , yes: function () {
                    layer.closeAll();
                }
                , btn2: function () {
                    var treeObj = $.fn.zTree.getZTreeObj("treeApplication");
                    var nodes = treeObj.getChangeCheckedNodes();
                    if (nodes.length < 1) {
                        layer.msg('请编辑要给该角色分配的资源!', {icon: 7});
                        return;
                    }
                    $.ajax({
                        url: basePathUrl + "/roleApplication/saveRoleApplication/" + data.id,
                        type: "POST",
                        dataType: "json",
                        contentType: "application/json;charse=UTF-8",
                        headers: {'Authorization': token},
                        data: JSON.stringify(nodes),
                        success: function (result) {
                            if (result.code === "200") {
                                layer.msg("保存资源成功!", {icon: 6});
                            }
                        },
                        error: function () {
                            layer.msg("保存资源失败!", {icon: 5})
                        }
                    })
                }
            });
        } else if (obj.event === 'detail') {        ④:这里就是今天要梳理的“组织”对应的数,来实现异步加载。
            $('#app')[0].reset()
            $('#app').attr("disabled", false);
            layer.open({
                type: 1
                , title: '绑定组织机构(请务必绑定到具体个人,否则绑定失效)'
                , maxmin: true
                , area: ['450px', '500px']
                , shade: 0
                , content: $('#app')
            });

            // ztree加载======================异步加载的这颗树================
            var zTreeObj;

            var setting = {
                async: {
                    enable: true,
                    type: "get",    //下面加载的这个url就是初始化树的接口,根据公司ID查询该公司的组织机构。
                    url: basePathUrl + "/organization/queryOrganizationUserTree?companyId="+companyId,   
                   // otherParam: ["companyId", companyId],
                    autoParam:["id"]   //这个id对应着点击某一个组织机构后,将点击的节点ID传到接口的ID,会自动获取点击ID,对应异步查询的接口
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                },
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    //radioType: "level"
                   chkboxType: {"Y": "s", "N": "s"},   //这里是节点的父子关联设置。
                    radioType: "all"
                },
                callback : {
                   // beforeAsync  : ztreeBeforeAsync,
                    onClick:ztreeOnAsyncSuccess,    //点击树节点出发的事件,也就是异步加载的接口(参数在上面的autoParam)
                    onAsyncSuccess : ztreeOnAsyncSuccess, //这个也要添加

                }
            };
            //初始化树============================================
            zTreeObj = $.fn.zTree.init($("#bindOrganization"), setting);  //注意,初始化树的时候,要加  # 号(获取的时候,不能加#,具体见下方)
        }

    })
});
//异步加载的方法
function ztreeOnAsyncSuccess(event, treeId, treeNode){
    //var url = basePathUrl + "/organization/findTreeUser?id=";  //这里ID对应上面的autoParm,这是根据组织Id查询此组织下面的人员。
    var url = basePathUrl + "/organization/findTreeUser?roleId="+window.mydata.id+"&id="
    if(treeNode == undefined){
        url += "1";  //默认ID是1.
    }
    else{
        url += treeNode.id; //动态获取选中节点的ID
    }
    $.ajax({
        type : "get",
        url : url,
        data : "",
        dataType : "json",
        async : true,
        success : function(jsonData) {
            console.log(jsonData+"  I am jsonData");
            console.log(typeof jsonData+"我是类型");
            if (jsonData != null) {
               // var data = jsonData.unitList;
                var datajson=JSON.stringify(jsonData);  //这里注意,添加树节点的时候,参数要为Object,所以要注意转换数据类型!
                var data=JSON.parse(datajson);
                console.log(data+"25252525252");
                if(data != null && data.length != 0){
                    if(treeNode == undefined){
                        //zTreeObj.addNodes(null,data,true);// 如果是根节点,那么就在null后面加载数据
                        $.fn.zTree.getZTreeObj("bindOrganization").addNodes(null,jsonData,true);
                    }
                    else{
                       // zTreeObj.addNodes(treeNode,jsonData,true);//如果是加载子节点,那么就是父节点下面加载
                        $.fn.zTree.getZTreeObj("bindOrganization").addNodes(treeNode,jsonData,true);  //这里注意,不要添加#
                        zTreeObj.updateNode(treeNode);
                    }
                }
                //$.fn.zTree.getZTreeObj("bindOrganization").expandAll(true);
                //zTreeObj.updateNode(treeNode);
                $.fn.zTree.getZTreeObj("bindOrganization").expandNode(treeNode,true, false, false);// 将新获取的子节点展开
            }
        },
        error : function() {
            alert("请求错误!");
        }
    });

};
function ztreeOnAsyncSuccess(event, treeId, treeNode){
    //var url = basePathUrl + "/organization/findTreeUser?id=";  //这里ID对应上面的autoParm,这是根据组织Id查询此组织下面的人员。
    var url = basePathUrl + "/organization/findTreeUser?roleId="+window.mydata.id+"&id="
    if(treeNode == undefined){
        url += "1";  //默认ID是1.
    }
    else{
        url += treeNode.id; //动态获取选中节点的ID
    }
    $.ajax({
        type : "get",
        url : url,
        data : "",
        dataType : "json",
        async : true,
        success : function(jsonData) {
            console.log(jsonData+"  I am jsonData");
            console.log(typeof jsonData+"我是类型");
            if (jsonData != null) {
               // var data = jsonData.unitList;
                var datajson=JSON.stringify(jsonData);  //这里注意,添加树节点的时候,参数要为Object,所以要注意转换数据类型!
                var data=JSON.parse(datajson);
                console.log(data+"25252525252");
                if(data != null && data.length != 0){
                    if(treeNode == undefined){
                        //zTreeObj.addNodes(null,data,true);// 如果是根节点,那么就在null后面加载数据
                        $.fn.zTree.getZTreeObj("bindOrganization").addNodes(null,jsonData,true);
                    }
                    else{
                       // zTreeObj.addNodes(treeNode,jsonData,true);//如果是加载子节点,那么就是父节点下面加载
                        $.fn.zTree.getZTreeObj("bindOrganization").addNodes(treeNode,jsonData,true);  //这里注意,不要添加#
                        zTreeObj.updateNode(treeNode);
                    }
                }
                //$.fn.zTree.getZTreeObj("bindOrganization").expandAll(true);
                //zTreeObj.updateNode(treeNode);
                $.fn.zTree.getZTreeObj("bindOrganization").expandNode(treeNode,true, false, false);// 将新获取的子节点展开
            }
        },
        error : function() {
            alert("请求错误!");
        }
    });

};

 

 加载初始化的树:(根据公司ID查询组织树)

Controller:

 @RequestMapping(value = {"/queryOrganizationUserTree"},method = RequestMethod.GET,produces="text/html;charset=UTF-8")
    @ResponseBody
    public String queryOrganizationUserTree(@RequestParam String companyId){
        //如果已经加载了树,就直接去查用户。
        String treeJson = "";
        try {
            List> bigTree = organizationFacade.queryOrganizationUserTree(companyId);
            treeJson = JacksonJsonUntil.objectToJson(bigTree);
        } catch (Exception e) {
            logger.error("查询组织机构树异常",e);
        }
        return treeJson;
    }

serviceImp:

        

@Override
    public List> queryOrganizationUserTree(String companyId) {
        //找出父节点的组织机构
        OrganizationExample organizationExample = new OrganizationExample();
        OrganizationCriteria criteria = organizationExample.createCriteria();
        criteria.andIsDeleteEqualTo((byte)0);
        criteria.andCompanyIdEqualTo(companyId);
        List organizationEntities = this.selectByExample(organizationExample);

        //result存放整颗树
        List> result = new ArrayList<>();
        //选出pid等于0的根节点
        if(!CollectionUtils.isEmpty(organizationEntities)){
            List parentList = organizationEntities.stream().filter(item -> "0".equals(item.getPId())).collect(Collectors.toList());
            //把根节点放在Mpa里面,并去调用递归算法去查询子树
            if(!CollectionUtils.isEmpty(parentList)){
                parentList.forEach(item->{
                    Map map = new HashMap<>();
                    map.put("id",item.getId());
                    map.put("pId",item.getPId());
                    map.put("name",item.getOrganizationName());
                    //map是查询出来的根节点。organizationentities是所有的节点。
                    this.getSonUseTree(map,organizationEntities);
                    result.add(map);
                });
            }

        }
        return result;
    }

    递归:

    

  private Map getSonUseTree(Map map,List itemList){
        //用来存放所有孩子集合
        List> sonList = new ArrayList<>();

        //选出某一个根节点下面的子树,递归。
        List son = itemList.stream().filter(item -> map.get("id").equals(item.getPId())).collect(Collectors.toList());

        //如果此节点的孩子不为空,则把孩子放在map里面,并加入到孩子集合里面。
        if(!son.isEmpty()){
            son.forEach(item->{
                Map sonMap = new HashMap<>();
                sonMap.put("id",item.getId());
                sonMap.put("pId",item.getPId());
                sonMap.put("name",item.getOrganizationName());
                sonList.add(sonMap);
                this.getSonUseTree(sonMap,itemList);
            });
        }

        if(!CollectionUtils.isEmpty(sonList)){
            map.put("children",sonList);
        }
        return map;
    }

 

 

异步加载的接口:(根据选中的组织机构的ID,查询下面的人员)

Controller:

       

@RequestMapping(value = {"/findTreeUser"},method = RequestMethod.GET,produces="text/html;charset=UTF-8")
    @ResponseBody
    public String findTreeUser(@RequestParam String id,@RequestParam String roleId){
        String treeJson = "";
        List> treeList;
        try {
            treeList = organizationFacade.findTreeUser(id,roleId);
            treeJson = JacksonJsonUntil.objectToJson(treeList);
        } catch (Exception e) {
            logger.error("查询组织机构树异常",e);
        }
        return treeJson;
    }

ServiceImp:

      

  @Override
    public List> findTreeUser(String id,String roleId) {
        //result存异步查询结果树
        List> result = new ArrayList<>();
        //查询该组织机构下的用户
        List sonUser=organizationDao.queryUserByOrgId(id);
        //查询已经绑定的该角色的用户。
        List hasBindList=new ArrayList<>();
        UserRoleExample example=new UserRoleExample();
        UserRoleCriteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleId);
        criteria.andIsDeleteEqualTo((byte)0);
        hasBindList= userRoleDao.selectByExample(example);

            if (!CollectionUtils.isEmpty(sonUser)){
                for (AllusersEntity allusersEntity : sonUser) {
                    Map map = new HashMap<>();
                    map.put("id",allusersEntity.getId());
                    map.put("pId",id);
                    map.put("name",allusersEntity.getUserName());
                    for (UserRoleEntity userRoleEntity : hasBindList) {
                        if(userRoleEntity.getUserId().equals(allusersEntity.getId())){
                            map.put("checked",true);
                        }
                    }
                    result.add(map);
                }
            }
        return result;
    }

 

      layUI  异步树加载就记录到这里,如有问题,请联系我,很高兴与您讨论。

 

推荐一个公众号,免费领架构师学习资料,每周更新优质文章,能学到很多。

你可能感兴趣的:(Layui之异步加载树)