使用jstree创建无限分级的树(ajax动态创建子节点)

首先来看一下效果

页面加载之初

image

节点全部展开后

image

首先数据库的表结构如下

image

其中Id为主键,PId为关联到自身的外键

两个字段均为GUID形式

层级关系主要靠这两个字段维护

其次需要有一个类型

    public class MenuType
    {
        public Guid Id { get; set; }
        public Guid PId { get; set; }
        public string MenuName { get; set; }
        public string Url { get; set; }
        public int OrderNum { get; set; }
        public int SonCount { get; set; }
    }
 

此类型比数据库表增加了一个属性

SonCount

这个属性用来记录当前节点的子节点的个数

注意:也可以把此属性放在数据库中,性能上会提升一些,但需要增加额外的代码来维护此字段

接下来看一下取数据的方式

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["Action"] == "AJAX")
            {
                var result = GetMenu(Request["pid"]);
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string sRet = serializer.Serialize(result);
                Response.Write(sRet);
                Response.End();
            }
        }
 

页面加载之初判断是否需要获取菜单数据

其中请求参数pid为客户端需要获取的节点ID

如果请求顶级节点,则此参数的值为00000000-0000-0000-0000-000000000000

GetMenu函数获取需要请求的节点数据

        private List<MenuType> GetMenu(string pid)
        {
            var result = new List<MenuType>();
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=SHU;User ID=sa;Password=allen;");
            conn.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = "select a.*,b.cout as count from Menu a left join (select COUNT(*) as cout,Menu.PId from Menu group by Menu.PId) as b on a.Id = b.PId  where a.PId = '" + pid + "' order by OrderNum";
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            while (dr.Read())
            {
                var obj = new MenuType();
                obj.Id =Guid.Parse(dr["Id"].ToString());
                obj.MenuName = dr["MenuName"].ToString();
                obj.OrderNum = Convert.ToInt32(dr["OrderNum"]);
                obj.PId = dr["PId"] == DBNull.Value ? Guid.Empty : Guid.Parse(dr["PId"].ToString());
                obj.Url = dr["Url"].ToString();
                obj.SonCount = dr["count"] == DBNull.Value ? 0 : Convert.ToInt32(dr["count"]);
                result.Add(obj);
            }
            return result;
        }
 

在本DEMO中使用JavaScriptSerializer来序列化菜单数组

前台的代码如下

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <link href="Scripts/themes/default/style.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script src="Scripts/jquery.jstree.js" type="text/javascript"></script>
    <script>
        $(function () {
            $.getJSON("/default.aspx?ACTION=AJAX&pid=00000000-0000-0000-0000-000000000000", function (result) {
                $.each(result, function (i, item) {
                    var typeN = item.SonCount > 0 ? "jstree-closed" : "jstree-leaf";
                    $("#tree").append("<li id='phtml_" + item.Id + "' class='" + typeN + "'><a href='#'>" + item.MenuName + "</a></li>");
                });
                $("#demo2").jstree({
                    "plugins": ["themes", "html_data", 'types', "ui", "checkbox"],
                    'core': { 'animation': 0 },
                    "types": { "types":
                                {
                                    "person": { "icon": { "image": "/Scripts/themes/default/person.png"} },
                                    "depar2": { "icon": { "image": "/Scripts/themes/default/depar2.png"} },
                                    "default": { "icon": { "image": "/Scripts/themes/default/depar1.png"} }
                                }
                    }
                }).bind("open_node.jstree", function (e, data) {
                    var id = data.rslt.obj[0].id;
                    if ($("#" + id + " li").length > 0) { return; }
                    $.getJSON("/default.aspx?ACTION=AJAX&pid=" + id.replace("phtml_", ""), function (result) {
                        var str = "<ul>"
                        $.each(result, function (i, item) {
                            var typeN = item.SonCount > 0 ? "jstree-closed" : "jstree-leaf";
                            var icon = item.SonCount > 0 ? "depar2" : "person";
                            str += "<li rel = '" + icon + "' id='phtml_" + item.Id + "' class='" + typeN + "'><a  href='#'> " + item.MenuName + "</a></li>";
                        });
                        str += "</ul>";
                        $("#" + id).append(str);
                        var tree = jQuery.jstree._reference("#" + id);
                        tree.refresh();
                        $("ins[class='jstree-checkbox jstree-icon']").removeClass("jstree-icon");
                        $(".jstree-checkbox").attr("style", "");
                    });
                });
            });
        });

    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div id="demo2">
    <ul id="tree">
    </ul>
    </div>
</asp:Content>

  

页面加载之初,先请求顶级节点

如果顶级节点的SonCount属性大于0

则使节点为闭合状态(样式为jstree-closed)

如果节点无子节点

则该节点的样式为jstree-leaf

当用户点击闭合状态的节点时,客户端发起请求

并把点击节点的ID传给后端,后端获取到点击节点的子节点后

通过append添加到点击节点下

至此,无限分级的树创建完成

其中不包含数据库

 

---------------------------------------------------------------------------

喜欢本文的,请点支持,有问题请在本文下评论,我会及时回复的

谢谢大家

posted @ 2012-05-29 14:30  liulun  阅读(16128)  评论(11编辑  收藏  举报