Jstree to create an infinite hierarchical tree "dynamic creation of child nodes based on Ajax" _javascript tips

Source: Internet
Author: User

The example in this article describes how Jstree creates an infinite hierarchical tree. Share to everyone for your reference, specific as follows:

First look at the effect

The beginning of the page load

After all nodes are expanded

First, the table structure of the database is as follows

Where the ID is the primary key, the PID is the foreign key associated to itself

Two fields are in GUID form

Hierarchical relationships are maintained primarily by these two fields

Second, you need to have a type

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;}
}

This type adds a property to the database table

Soncount

This property is used to record the number of child nodes of the current node

Note: You can also put this property in the database, improve performance, but need to add additional code to maintain this field

Next look at the way the data is taken

protected void Page_Load (object sender, EventArgs e)
{
  if (request["Action" = = "AJAX")
  {
    var result = Ge Tmenu (request["pid");
    JavaScriptSerializer serializer = new JavaScriptSerializer ();
    String Sret = serializer. Serialize (result);
    Response.Write (Sret);
    Response.End ();
  }


At the beginning of the page load to determine if you need to get menu data

Where the request parameter PID is the node ID that the client needs to obtain

If the top-level node is requested, the value of this parameter is 00000000-0000-0000-0000-000000000000

GetMenu function Gets the node data that needs to be requested

Private list<menutype> GetMenu (string pid) {var result = new list<menutype> (); SqlConnection conn = new SqlConnection ("Data source=.;i Nitial 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;}

 

Use JavaScriptSerializer to serialize menu arrays in this demo

The front desk code is as follows

<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 ': {' Animati On ': 0}, ' types ': {' types ': {' person ': {' ico 'N ": {" 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> ' $.EAC H (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>

At the beginning of the page load, first request the top-level node

If the Soncount property of the top-level node is greater than 0

Causes the node to be closed (style jstree-closed)

If the node has no child nodes

The style of the node is Jstree-leaf

When the user clicks on the closed node, the client initiates the request

The ID of the click node is passed to the backend, and the back end gets to the sub node of the clicked node

Add to click Node via append

At this point, the tree creation of an infinite rating is complete

It does not contain a database

More readers interested in JavaScript-related content can view the site topics: "JavaScript object-oriented Tutorial", "JavaScript traversal algorithm and tips summary", "JavaScript switching effects and techniques summary", " JavaScript Search Algorithm Tips Summary, "JavaScript animation effects and techniques Summary", "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary" and "JavaScript Mathematical operation Summary"

I hope this article will help you with JavaScript programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.