Implementation of dynamic tree structure with Ajax

Source: Internet
Author: User
Tags add format array object file system sql object model string
ajax| Dynamic | tree-structured tree structure is a kind of widely used data structure. The genealogy of Clan and the organization form of modern enterprise in human society are all tree-shaped structure. In the field of computer, the management structure of files in file system, the page table in memory management, the index in database, etc. are all tree-type structure. With the rapid development of Internet, the application of tree-type structure in browser/server (Browser/server, b/s) is more and more extensive.

At present, there are two kinds of tree structures which are widely existed and applied on Internet: static and dynamic structure. Static structure exists most, realizes simple, however, static causes can not change the structure and content of tree, can not reflect the change of node information of tree, while the implementation of relatively complex dynamic tree, although can dynamically add, delete, update node information, but most can not directly drag and drop nodes to change the structure of the tree and the order between nodes, and repeatedly refresh the entire page, to the user maintenance has brought a lot of inconvenience. This paper presents a solution of dynamically loading nodes based on Ajax (asynchronous JavaScript and XML). The realization uses the Java-EE multi-layer architecture, the tree node description information uses the database storage, the Extensible Markup Language (extensible Markup Language, for short XML) displays to the JavaScript parsing, supports adds, deletes, updates the node information without the refresh, and drag-and-drop nodes to change the structure of the tree and the order between nodes. The 1th part of this paper introduces the Ajax technology, the 2nd part introduces the technology realization process of the scheme in detail, and the 3rd part analyzes the efficiency of the program.

1. Introduction to Ajax

The earliest author of the Ajax concept, Jesse James Garrett, said: Ajax is not a new language or technology, it is actually several technologies in a certain way to play their role in a common collaboration, it includes:

• Standardize presentation using Extended Hypermedia Markup Language (eXtended hypertext Markup Language, abbreviated XHTML) and cascading style sheets (cascading style Sheet, short CSS);

• Implement dynamic display and interaction using the Document Object model, the text, referred to as DOM;

• Use Extensible Markup Language (extensible Markup Language, abbreviated XML) and Extensible Stylesheet Conversion (extensible Stylesheet Language Transformation, For short, XSLT) for data exchange and processing;

• Asynchronous data reading using the XMLHTTP component XMLHttpRequest object;

• Finally, bind and process all data with JavaScript.

Ajax works as shown in Figure 1, which is equivalent to adding a middle tier between the user and the server, allowing the user to respond asynchronously to the server. Not all user requests are submitted to the server, such as data validation and processing, which are handled by the Ajax engine, and the Ajax engine submits the request to the server only if it is determined that new data needs to be read from the server. In this way, some server burden of the work to the client, using the client idle processing capacity to deal with, reduce the burden of server and bandwidth, so as to save the ISP space and bandwidth rental costs.


Figure 1 Comparison of Web applications using Ajax (a) and Ajax (b)

2. Overall design plan

Traditional server programs use Model 1 development models, usually the business logic, server-side processing and HTML code together to express the rapid completion of application development. Model 1 in the small scale application development when the advantage is obvious, but the application implementation is generally based on the process, a group of server Pages to implement a process, if the process changes will lead to a number of local changes, very detrimental to the application of the extension and update. In addition, the business logic and presentation logic are mixed in the server Pages, coupled tightly and cannot be modularized, resulting in the code not being reused.

Model 2 solves these problems, it is an object-oriented MVC pattern (Model-view-controller, model-View-Controller) in Web development application, model represents the application of the business logic, View is the application of the presentation layer page, Controller is a process control that provides applications. The MVC design pattern divides the application logic, the processing process and the display logic into different components and modules, which can be interacted and reused among the components.

This scheme adopts the multi-layer architecture of Java EE, which divides the presentation layer, the business logic layer and the data layer into different modules in the design with the struts framework. The presentation layer focuses on the appearance of the tree, the business logic layer is the server-side processing program, the processing tree generation, the change, in order to reduce the coupling, the program is all modular implementation, not the representation page embedded server program; The model layer is the storage and presentation of data. The implementation of each layer is described below.

2.1 Presentation Layer Implementation

Similar to the Windows Explorer folder mode, the picture style of the node is shown in table 1. For each node's DHTML code, you need to include the location of the node, a leading picture, a style, other actions for that node, and so on. Also, for the consistency of the node display, some leading images are required.

Table 1 A picture style sheet before the tree node


A DIV (Division) container is included for the tree's non leaf nodes, picture and node information, etc. DIV and other containers are the basis of DHTML, using it to manipulate its properties through scripting, such as setting its style's display property to control the expansion and concealment of child nodes. The location of the node, the leading picture, the style, and other actions for the node are placed in the container, for example:
DIV ID =mparentid>
IMG align = center border = 0 onclick =″nodeexpand (' leafid ') ″name = m1tree src =′tplus.gif′>
IMG align = center border = 0 name = M1folder src =′folderclosed. gif′> Computer College </DIV>

Leaf nodes do not need direct output from the container.

When the "+", "-" picture is clicked on a node, the display property of the Div's style style controls the expansion and concealment of the child nodes. Display: "None" (hidden, invisible), display: "Block" (display). The relevant JavaScript code is as follows:
if (ExpandChild.style.display = =″none″) {
Currently hidden, performing an unwind action
This. Loading (ParentObject);//Determine whether the data for this branch has been loaded
ExpandChild.style.display =″block″;
if (Para2 = =″last″)
Parentobject.src =″lminus. Gif″; Last node
Else
Parentobject.src =″tminus. Gif″; Show ┠
Expandfolder.src =″folderopen. Gif″;
}else {
Hide all child nodes of the current node
ExpandChild.style.display =″none″;
if (Para2 = =″last″)
Parentobject.src =″lplus. Gif″;
Else
Parentobject.src =″tplus. Gif″;
Expandfolder.src =″folderclosed. Gif″;
}

2.2 Structure design of tree table

We take the database as the carrier to record the change of the node, the tree table structure should have at least the following fields: the number of nodes (CLASSID), the description of the node (ClassName), the number of the parent node (ParentID), these are the information necessary to construct the tree structure. The Class code (CLASSCODE) of the node, the level of the node (classlevel), the leaf node (terminated), and other auxiliary fields are also introduced, the order of the nodes is recorded, and the entity diagram is shown in Figure 3.


Fig. 3 Schematic diagram of tree table structure

The time complexity of the


Tree traversal is O ( N ). However, after the tree information is stored in the database, it can not traverse the tree in the traditional way, you must use SQL statements to access the contents of the database table, and the more the amount of data, the more resources consumed, the longer the user waiting time. If the unordered data is read from the database, on the server side, the sorted tree must be sent to the client for display. Therefore, it is a good idea to read the sorted tree from the database.

We know that string sorting is in dictionary order. Combined with the characteristics of SQL statements and tree structure, the class code of the nodes in the database table is in the form of multilevel strings, such as AAABBBCCC, starting from the root node, adding one level for each downward-level string, and the child node class code begins with the parent node class code and then begins the class code. The nodes of the same sibling are numbered in the order in which they were generated, such as the class code for the next class of AAA children, Aaaaaa,aaaaab, Aaaaab children nodes for AAAAABAAA, Aaaaabaab, etc. The width of each level of numbered characters is associated with the actual application, for example, there are 263 nodes at the aaa~zzz level, and if not enough, add one more character for encoding. The ingenious numbering method. Makes the complete First order tree one at a time after executing the SQL statement SELECT * from Tree_class ordered by Classcode.

2.3 Business Logic Layer design

2.3.1 Dynamic Loading technology

If you get the complete First order tree at once, construct XML to provide JavaScript parsing, the larger the amount of data, The more resources consumed, the longer the client response latency, so for large data trees, the dynamic loading method, that is, each click the "+" picture, to determine whether the child node data is loaded, if not loaded by the Ajax XMLHTTP component XMLHttpRequest object asynchronous send request , connect the server to execute the SQL statement "SELECT * from tree_class where parent =?" ORDER by Classcode gets the node data. The relevant JavaScript code is as follows:
/* To determine whether the data has been loaded, the access server loading data is not loaded */

Dhtmltree.prototype.loading=function (pobject) {
if ((pobject.xmlload==0) && (this. Xmlsource) && (!this).  xmlloading)) {
pobject.xmlload=1;
This.loadxml (this. Xmlsource+geturlsymbol (this. Xmlsource) + "id=" +escape (pobject.id));
}
}
Dtmlxmlobject.prototype.loadxml=function (URL) {//Load data
try {
This.xmldoc = new XMLHttpRequest ();
/* Asynchronously connects to URL loading data via get method */
This.xmlDoc.open ("Get", url,true);//true: Asynchronous; false: Sync
this.xmlDoc.send (null); br>} catch (e) {
This.xmldoc = new ActiveXObject ("Microsoft.XMLHTTP");//Use IE
This.xmlDoc.open ("Get", url,true) ;//true: Asynchronous; false: Synchronizing
This.xmlDoc.send (null);
}
return This.xmlDoc.responseXML;
}

ParentID the sequence of children of the same parent node at a time, encapsulating the document structure as a tree in XML format, for example:



DhtmlTreeObject.prototype.insertItem () provided to JavaScript to parse and organize the HTML output node, where child:1 represents a child node, 0 means No child nodes, and im0 represents an icon with no child nodes; Im1 represents a child node and opens a section Icon when IM2 represents a child node and when it is closed, so you can also customize the icon when you construct the XML.

Construction of 2.3.2 Tree-type structure

Returned from the database is an ordered first order tree, and XML is a complete tree structure document, so the tree data into a predefined XML format, just start from the root node, traverse the tree, you can build all the trees. The relevant JavaScript code is as follows:
/* Dynamic Loading Tree construction method * *

Dtmlxmlobject.prototype.constructtree=function () {

XML data obtained by dynamic loading is used to parse tree-type data

var node=this. Xmlloader.getxmltopnode ("Tree");

var parentid=node.getattribute ("id");

for (Var i=0;i

if ((node.childnodes[i].nodetype==1) && (node.childnodes[i].tagname = = "Leaf")) {
var name=node.childnodes[i].getattribute ("text");
............
var temp=dhtmlobject.a0find (ParentID);//Get Parent Node Object
Temp. xmlload=1;//already loaded
Constructing an HTML output node
Dhtmlobject.insertitem (PARENTID,CID,NAME,IM0,IM1,IM2,CHD);
Dhtmlobject.adddragger = this;//Set the object to drag and drop
};
}

Maintenance of 2.3.3 Tree-type structure

When maintaining a tree structure table, the deletion node is simpler, and the SQL statement is: "Delete from Tree_class where Classcode like′" + Classcode + "%′" to remove the node and the child; , and insert child nodes three cases, the first two cases need to update the recursive update category code, the latter only need to find the parent node's child's maximum class code plus 1, as the class code to increase the node, and drag and drop to change the structure of the tree, Simply update the parentid of the dragged node to the classid of the target node, and the corresponding SQL statement is: "Update tree_class Set parentid =" + classidto+ "where classid =" + CLASSIDFR Om.

3. Efficiency Analysis

For the storage of the tree there are generally two forms: two-dimensional tables and linked lists, traversal methods generally have depth traversal and breadth traversal two ways, the time complexity of the traversal is O (N)。 When using a two-dimensional table, the subscript of an array in memory can accurately locate the parent node of the node and the array subscript where the sibling node is located. The location of the nodes in the database is also accurate, but when the node information is read from the database into memory, if the node information cannot be positioned through the memory array, then you must traverse the search for a node,NThe time to look for a node in a node is O (n/2),NThe time complexity of sorting a node will be O (N 2/2, this is the general implementation of the B/s mode of the tree structure inefficient reasons. This scheme uses dictionary ordinal numbering scheme, makes the tree that obtains from the database is already sorted, the direct traverse builds the client page program, the time complexity is O ( n ).

4. Conclusion

This paper discusses the implementation scheme of dynamic tree structure based on Ajax, the node information of the dynamic maintenance tree without refreshing is supported, the node structure and order of the tree are supported by the drag-and-drop node, and the database storage node information is used to ensure the generality of the scheme, in addition, the node information of XML description tree is combined. Any information described in the XML document intended for this scenario can be displayed through the tree. This program has been applied in the digital orientation system of our school and the information system of the common People's large pharmacy.



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.