Home > php教程 > PHP开发 > Solving the problem of echoing new characters and editing characters in Ztree

Solving the problem of echoing new characters and editing characters in Ztree

高洛峰
Release: 2016-12-09 09:15:35
Original
1490 people have browsed it

Ztree was used in the project recently. It took a while to echo, so I recorded it for next time reference.

1. Use ztree to load permissions for new roles. Since there are not many permissions, you can load them all directly.

Rendering:

Solving the problem of echoing new characters and editing characters in Ztree

Specific ztree code involved:

Import in jsp:/js/ztree/zTreeStyle.css and js/ztree/jquery.ztree.all-3.5.js

page addition

< ;ul id="functionTree" class="ztree">

js code (the layer pop-up effect is added to this js):

<script>
    $(function() {
      // 授权树初始化
      var setting = {
        data : {
          key : {
            title : "t"
          },
          simpleData : {
            enable : true
          }
        },
        check : {//使用ztree选中效果
          enable : true,
        }
      };
      $.ajax({
        url : &#39;${pageContext.request.contextPath}/rest/sys/getAllFunction&#39;,//发送ajax请求加载权限数据
        type : &#39;get&#39;,
        dataType : &#39;json&#39;,
        success : function(data) {//data就是服务端返回的权限数据
          //var zNodes = eval("(" + data + ")");
          //使用权限数据初始化ztree
          $.fn.zTree.init($("#functionTree"), setting, data);
        },
        error : function(msg) {
          alert(&#39;树加载异常!&#39;);
        }
      });
        
      //确定添加按钮
      $("#btn_submit").click(function() {
        if(checkHousetype()){
          //获得ztree对象
          var treeObj = $.fn.zTree.getZTreeObj("functionTree");
          //获得当前ztree对象选中的节点数组
          var nodes = treeObj.getCheckedNodes(true);//在提交表单之前将选中的checkbox收集
          //循环数组,获得节点的ID,拼接成字符串使用逗号分隔
          var array = new Array();
          for(var i=0;i<nodes.length;i++){
            array.push(nodes[i].id);
          }
          var ids = array.join(",");
          $("input[name=funcitonIds]").val(ids);
  
          var formData = new FormData($("#formproject")[0]);
           $.ajax({
            type : "POST",
            url : "${pageContext.request.contextPath }/rest/sys/addRole",
//           data : $("#formproject").serialize(),
            data:formData,
            contentType: false,
            processData: false,
            statusCode : {
              201 : function() {
                layer.msg(&#39;新增角色成功!&#39;, {icon: 6,time:1500},function(){
                  location.href = "${pageContext.request.contextPath }/rest/sys/page/rolelist";
                })
              },
              400 : function() {
                layer.msg(&#39;提交的参数不合法&#39;, {time:1500});
              },
              500 : function() {
                layer.msg(&#39;网络异常,请稍候再试!&#39;, {time:1500});
              }
            }
          });
        }
      });
    });
      
      
      
    //校验
    function checkHousetype(){
      var flag = true ;
      //关键字
      if($("#code").val()==&#39;&#39;){
        flag = false ;
        layer.msg(&#39;请输入关键字&#39;, {time:1500});
        return flag ;
      }
      //名称
      if($("#name").val()==&#39;&#39;){
        flag = false ;
        layer.msg(&#39;请输入角色名称&#39;, {time:1500});
        return flag ;
      }
        
      return flag ;
    }
  </script>
Copy after login

Ztree format in permissions:

private String id;
private String name;
private String code;
private String description;
  
// private String page;
//private String generatemenu;
//private String zindex;
  
private String pid;
private boolean isParent;
  
//ztree组件需要格式
public String getpId() {
   return this.pid==null?"0":this.pid;
 }
  
 ......
Copy after login

2. Edit role echo Ztree

js code:

<script>
   var zNodes;
    var setting = {
        check: {
          enable: true
        },
        data: {
          simpleData: {
            enable: true
          }
        }
      };
    //当页面加载完毕,向后台发送ajax请求,获取用户id为1的用户所拥有的权限
    //(这里要显示所有权限,该id用户的权限回显时,被自动选中),这里的用户id为1仅做测试使用,实际开发中会传值
    function loadPower(roleId){
          $.ajax({
            type:"post",
            url:"${pageContext.request.contextPath }/rest/sys/queryFunByRoleId",
            data:{"roleId":roleId},
            async:false,
            dataType:"json",
            success:function(data){
              zNodes=data;
            }
          })
    }
    $(function() {
      // 授权树初始化
      var setting = {
        data : {
          key : {
            title : "t"
          },
          simpleData : {
            enable : true
          }
        },
        check : {//使用ztree选中效果
          enable : true,
        }
      };
      //页面加载完毕时加载此方法
      $(document).ready(function(){
        var id = $("#roleId").val();
        loadPower(id);
        $.fn.zTree.init($("#functionTree"), setting, zNodes);
      });
        
      //确定添加按钮
      $("#btn_submit").click(function() {
        if(checkHousetype()){
          //获得ztree对象
          var treeObj = $.fn.zTree.getZTreeObj("functionTree");
          //获得当前ztree对象选中的节点数组
          var nodes = treeObj.getCheckedNodes(true);//在提交表单之前将选中的checkbox收集
          //循环数组,获得节点的ID,拼接成字符串使用逗号分隔
          var array = new Array();
          for(var i=0;i<nodes.length;i++){
            array.push(nodes[i].id);
          }
          var ids = array.join(",");
          $("input[name=funcitonIds]").val(ids);
  
          var formData = new FormData($("#formproject")[0]);
           $.ajax({
            type : "POST",
            url : "${pageContext.request.contextPath }/rest/sys/eidtRole",
//           data : $("#formproject").serialize(),
            data:formData,
            contentType: false,
            processData: false,
            statusCode : {
              201 : function() {
                layer.msg(&#39;编辑角色成功!&#39;, {icon: 6,time:1500},function(){
                  location.href = "${pageContext.request.contextPath }/rest/sys/page/rolelist";
                })
              },
              400 : function() {
                layer.msg(&#39;提交的参数不合法&#39;, {time:1500});
              },
              500 : function() {
                layer.msg(&#39;网络异常,请稍候再试!&#39;, {time:1500});
              }
            }
          });
        }
      });
    });
      
      
      
    //校验
    function checkHousetype(){
      var flag = true ;
      //关键字
      if($("#code").val()==&#39;&#39;){
        flag = false ;
        layer.msg(&#39;请输入关键字&#39;, {time:1500});
        return flag ;
      }
      //名称
      if($("#name").val()==&#39;&#39;){
        flag = false ;
        layer.msg(&#39;请输入角色名称&#39;, {time:1500});
        return flag ;
      }
        
      return flag ;
    }
  </script>
Copy after login

java background:

controller:

/**
   * 编辑角色,回显角色权限
   * @param roleId
   * @return
   */
  @RequestMapping(value = "queryFunByRoleId", method = RequestMethod.POST)
  public ResponseEntity<List<Map<String, Object>>> queryFunByRoleId(String roleId) {
    try {
      if(StringUtils.isBlank(roleId)){
        // 返回400
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
      }
      return ResponseEntity.ok(sysService.queryFunByRoleId(roleId));
    } catch (Exception e) {
      e.printStackTrace();
    }
    // 出错 500
    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
  }
Copy after login

service :

Due to the contains method correction in List The age check failed, and I didn’t worry about the reason. I wrote the verification based on the ID

/**
   * zTree v3回显
   * 初始化化权限树
   * 拼接treeNode属性
   */
  @Transactional(readOnly=true)
  public List<Map<String, Object>> queryFunByRoleId(String roleId) {
    //查询所有权限
    List<AuthFunction> functions = queryAllAuthFunction();
    //查询指定角色的权限
    List<AuthFunction> functionsByRoleId = findFunctionByRoleId(roleId);
    //包装zTree
      
    List<Map<String, Object>> list =new ArrayList<Map<String, Object>>();
    Map<String, Object>map=null;
    for(int i=0;i<functions.size();i++){
      map=new HashMap<>();
      //Role role=functions.get(i);
      AuthFunction fun = functions.get(i);
      map.put("id", fun.getId());
      map.put("pId", fun.getpId());
      map.put("name", fun.getName());
      map.put("isParent", fun.getIsParent());
      //判断指定用户的角色是否在所有角色中包含,有则设置checked=true.
      if(functionsByRoleId != null && functionsByRoleId.size()>0 && ListIsContainsObj(functionsByRoleId,fun)){
        map.put("checked",true);
      }else {
        map.put("checked",false);
      }
      list.add(map);
    }
    return list;
  }
    
  //校验全部权限中是否有某个权限,有返回true
  private boolean ListIsContainsObj(List<AuthFunction> functions, AuthFunction fun) {
    if(fun == null || functions == null || functions.size()<=0){
      return false;
    }
    for (AuthFunction authFunction : functions) {
      if(fun.getId().equals(authFunction.getId())){
        return true;
      }
    }
    return false;
  }
Copy after login


Related labels:
source:php.cn
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template