• 组织架构树的实现,前端和后端处理逻辑


    渲染结果

    第一种情况:后台处理了数据,前台只需要展示(后台返还的结果就是一个数组树)

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <title>组织架构</title>
      <link rel="stylesheet" href="./lib/jquery.jOrgChart.css">
      <script src="./lib/jquery.js"></script>
      <script src="./lib/jquery.jOrgChart.js"></script>
      <script src="./lib/jquery-ui.min.js"></script>
      <style>
        a {
          text-decoration: none;
          color: #fff;
          font-size: 12px;
        }
    
        .jOrgChart .node {
          width: 120px;
          height: 50px;
          line-height: 50px;
          border-radius: 4px;
          margin: 0 8px;
        }
      </style>
    </head>
    
    <body>
      <!--显示组织架构图-->
      <div id='jOrgChart'></div>
    
      <script type='text/javascript'>
        $(function () {
          /**
           * 数据返回
           * 测试数据源
           * json-server .data02.json --port 3003
           */
          $.ajax({
            url: "http://localhost:3003/data",
            type: 'GET',
            dataType: 'JSON',
            data: {
              action: 'org_select'
            },
            success: function (result) {
              console.log(result)
              var showlist = $("<ul id='org' style='display:none'></ul>");
    
              showall(result, showlist);
              $("#jOrgChart").append(showlist);
    
              $("#org").jOrgChart({
                chartElement: '#jOrgChart', //指定在某个dom生成jorgchart
                dragAndDrop: false //设置是否可拖动
              });
    
              function showall(result, parent) {
                $.each(result, function (index, val) {
                  if (val.childrens.length > 0) {
                    var li = $("<li></li>");
                    li.append("<a href='javascript:void(0)' onclick=getOrgId(" + val.id + ");>" + val.name +
                      "</a>").append(
                      "<ul></ul>").appendTo(parent);
                    //递归显示
                    showall(val.childrens, $(li).children().eq(1));
                  } else {
                    $("<li></li>").append("<a href='javascript:void(0)' onclick=getOrgId(" + val.id + ");>" +
                      val.name +
                      "</a>").appendTo(parent);
                  }
                });
              }
    
              function getOrgId(val) {
                console.log(val);
              }
            }
          });
        });
      </script>
    </body>
    
    </html>

    第二种情况:后台以单个对象的形式返还全部的数据,需要前端根据关系进行处理

    后台返还的数据

    经过前台处理后的数据

    代码如下

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <link rel="stylesheet" href="./lib/jquery.jOrgChart.css">
      <script src="./lib/jquery.js"></script>
      <script src="./lib/jquery.jOrgChart.js"></script>
      <script src="./lib/jquery-ui.min.js"></script>
      <style>
        a {
          text-decoration: none;
          color: #fff;
          font-size: 12px;
        }
    
        .jOrgChart .node {
          width: 100px;
          height: 50px;
          line-height: 50px;
          border-radius: 4px;
          margin: 0 8px;
        }
    
        #jOrgChart {
          width: 600px;
          height: 600px;
          overflow-x: scroll;
        }
    
        /* 浏览器滚动条样式 */
        ::-webkit-scrollbar {
          width: 4px;
          height: 4px;
        }
    
        ::-webkit-scrollbar-track {
          background: rgb(255, 255, 255);
          border-radius: 8px;
        }
    
        ::-webkit-scrollbar-thumb {
          background: rgb(201, 201, 202);
          border-radius: 8px;
        }
    
        ::-webkit-scrollbar-thumb:hover {
          background: rgb(162, 162, 163);
        }
      </style>
    </head>
    
    <body>
      <!--显示组织架构图-->
      <div id='jOrgChart'></div>
    
      <script>
        $(function () {
          /**
           * 数据返回 
           * 默认端口3000
           * 端口被我修改成了3002
           * json-server .data01.json --port 3002
           * **/
          $.ajax({
            url: "http://localhost:3002/children",
            type: 'GET',
            dataType: 'JSON',
            data: {
              action: 'org_select'
            },
            success: function (_data) {
              console.log(_data)
              var node = {
                id: _data[0].fatherId,
                pid: _data[0].sonId,
                name: _data[0].name,
                childrens: []
              };
              getAreaTree(_data, node);
    
              function getAreaTree(data, pnode) {
                var _Name = [];
                var temp = {
                  id: "",
                  pid: "",
                  name: "",
                  childrens: []
                };
                for (var i = 0; i < data.length; i++) {
                  if (data[i].sonId == 0 && pnode.id == 0) {
                    temp = {};
                    if (_Name.indexOf(data[i].name) >= 0) {
                      continue;
                    }
                    _Name.push(data[i].name);
                    temp = {
                      id: data[i].fatherId,
                      pid: data[i].sonId,
                      name: data[i].name,
                      childrens: []
                    };
                    pnode.childrens.push(temp);
                    getAreaTree(data, pnode.childrens[pnode.childrens.length - 1]);
                  } else if (data[i].sonId == pnode.id) {
                    temp = {
                      id: data[i].fatherId,
                      pid: data[i].sonId,
                      name: data[i].name,
                      childrens: []
                    };
                    pnode.childrens.push(temp);
                    getAreaTree(data, pnode.childrens[pnode.childrens.length - 1]);
                  }
                }
              }
              console.log(node)
              // 把对象转成数组(为了length)
              function objToArr(node) {
                var nodeArr = []
                nodeArr.push(node)
                return nodeArr
              }
              var dd = objToArr(node)
              console.log(objToArr(node))
    
              // 渲染组织结构
              var showlist = $("<ul id='org' style='display:none'></ul>");
              showall(dd, showlist);
              $("#jOrgChart").append(showlist);
              $("#org").jOrgChart({
                //指定在某个dom生成jorgchart
                chartElement: '#jOrgChart',
                //设置是否可拖动
                dragAndDrop: false
              });
    
              function showall(dd, parent) {
                $.each(dd, function (index, val) {
                  console.log(val)
                  if (val.childrens.length > 0) {
    
                    var li = $("<li></li>");
                    li.append("<a href='javascript:void(0)' onclick=getOrgId(" + val.id + ");>" + val.name +
                      "</a>").append(
                      "<ul></ul>").appendTo(parent);
                    //递归显示
                    showall(val.childrens, $(li).children().eq(1));
                  } else {
                    $("<li></li>").append("<a href='javascript:void(0)' onclick=getOrgId(" + val.id + ");>" +
                      val.name +
                      "</a>").appendTo(parent);
                  }
                });
              }
            }
          });
        })
      </script>
    </body>
    </html>

    后端处理结果的逻辑

     第一种方式:

     [WebMethod]
            public string getTree()
            {
                string msg = "";
                try
                {
                    string sql = "select * from tb_customer";
                    DataTable dt = SqlHelper.ExecuteDataTable(sql);
                    IList<Area> list = null;
                    if (dt.Rows.Count > 0)
                    {
                        list = Table2List(dt);
                    }
                    Tree tree = new Tree()
                    {
                        id = list[0].fatherId,
                        pid = list[0].sonId,
                        text = list[0].name,
                        children=new List<Tree>()
                    };
                    string name = "";
                   tree= GetTree(list, tree, name);
                   msg = JsonConvert.SerializeObject(tree);
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
                return msg;
            }
            public Tree GetTree(IList<Area> list ,Tree pnode,string _name) 
            {
                Tree temp = new Tree();
                foreach (Area model in list) 
                {
                    if (model.sonId == 0 && pnode.id == 0) 
                    {
                        if (_name==model.name)
                           {
                               continue;
                           }
                        temp = new Tree()
                         {
                             id = model.fatherId,
                             pid = model.sonId,
                             text = model.name,
                             children = new List<Tree>()
                         };
                        _name =model.name;
                         pnode.children.Add(temp);
                         GetTree(list, pnode.children[pnode.children.Count - 1], _name);
                    }
                    else if (model.sonId == pnode.id) 
                    {
     
     
                          temp = new Tree()
                         {
                             id = model.fatherId,
                             pid = model.sonId,
                             text = model.name,
                             children = new List<Tree>()
                         };
                       pnode.children.Add(temp);
                       GetTree(list, pnode.children[pnode.children.Count - 1], _name);
                    }
                }
                return pnode;
            }
            public static IList<Area> Table2List(DataTable dt)
            {
                IList<Area> ts = new List<Area>();// 定义集合
                Type type = typeof(Area); // 获得此模型的类型
                string tempName = "";
                foreach (DataRow dr in dt.Rows)
                {
                    Area t = new Area();
                    PropertyInfo[] propertys = t.GetType().GetProperties();// 获得此模型的公共属性
                    foreach (PropertyInfo pi in propertys)
                    {
                        tempName = pi.Name;
                        if (dt.Columns.Contains(tempName))
                        {
                            if (!pi.CanWrite) continue;
                            object value = dr[tempName];
                            if (value != DBNull.Value)
                                pi.SetValue(t, value, null);
                        }
                    }
                    ts.Add(t);
                }
                return ts;
            }
    <pre name="code" class="csharp">    
        public class Tree
        {
            public int id { get;set;}
     
            public int pid { get;set;}
     
            public string text { get;set;}
     
            public List<Tree> children { get;set;}
     
        }

    第二种方式:利用了公司内部封装的一些方法

     

    using SmartA8.Common.Attributes;
    using SmartA8.Entities.A8SystemEntities;
    using System;
    using System.Linq;
    using System.Web.Script.Serialization;
    using System.Collections.Generic;
    using SmartA8.Models.Builders;
    
    namespace SmartA8.Models
    {
        [ModelCast(ClassName = "customer")]
        public class CustomerFirstModel
        {
            private IDAL.IA8SystemDAO A8SystemDAO = DALFactory.DataAccess.CreateA8SystemDAO();
    
            [ModelCast(PropertyName = "CustomerId")]
            public int CustomerId { get; set; }
    
            [ModelCast(PropertyName = "CompanyName")]
            public string CompanyName { get; set; }
    
            [ModelCast(PropertyName = "ParentCustomerId")]
            public int  ParentCustomerId { get; set; }
    
            [ModelCast(PropertyName = "IsUsing")]
            public bool IsUsing { get; set; }
    
            public List<CustomerFirstModel> Childrens
            {
                get {
                    List<Customer > ccCustomer = A8SystemDAO.FindAll<Customer>(g => g.ParentCustomerId == CustomerId).ToList();
                    return  BaseBuilder.Cast<CustomerFirstModel, Customer>(ccCustomer);
                }
            }
        }
    }
     #region
            //组织架构
            public OperateResult GetGeneratorSetOrganList(string username, SearchGeneratorSetOrganModel model = null)
            {
                UserProfile user = A8SystemDAO.FindAll<UserProfile>(u => u.UserName == username).FirstOrDefault();
                int customerId = user.CustomerNo;
                if (model != null && model.CustomerId != 0) customerId = model.CustomerId;
                Customer FirstCustomer = A8SystemDAO.FindAll<Customer>(g => g.CustomerId == customerId).FirstOrDefault();
                CustomerFirstModel CustomerModel = BaseBuilder.Cast<CustomerFirstModel, Customer>(FirstCustomer);
                return OperateResult.Success("", CustomerModel);
            }
     #endregion
  • 相关阅读:
    博客写作技巧及规范
    2020年中总结
    运维笔记(一)——磁盘挂载与逻辑卷扩容
    mysql设计与优化(二)——配置主从
    mysql设计与优化(一)
    日志处理(一)
    坑爹问题—360自动填充账户密码
    mysql设计与优化
    java并发-ConcurrentMap
    FastDfs配置nginx
  • 原文地址:https://www.cnblogs.com/m1754171640/p/10844982.html
Copyright © 2020-2023  润新知