Design and Implementation of Dynamic Tree Structure Based on AJAX

Source: Internet
Author: User
Tags types of tables
Tree structure is a type of widely used data structure. The Genealogy of clan in human society and the organization form of modern enterprises are tree structures. In the computer field, the file management structure in the file system, the page table in the memory management, and the index in the database are also tree structures. With the rapid development of the Internet, tree structure is widely used in browser/server (Browser/Server) application systems.

Currently, tree structures widely used on the Internet are generally divided into two types: Static and Dynamic structures. Static structures have the largest number of features and are easy to implement. However, static structures cannot change the structure and content of the tree and cannot reflect the changes in node information of the tree. Instead, a relatively complex dynamic structure tree is implemented, although node information can be dynamically added, deleted, or updated, most nodes cannot be directly dragged and dropped to change the tree structure and order between nodes, and the entire page is refreshed repeatedly, it brings a lot of inconvenience to user maintenance. This article proposes a general and dynamic loading node solution based on AJAX (Asynchronous JavaScript and XML. The implementation adopts the J2EE multi-layer architecture. The description information of the Tree node is stored in the database and presented to JavaScript for parsing by the Extensible Markup Language (XML, supports addition, deletion, and updating of node information without any additional traffic, and drag and drop nodes to change the tree structure and order between nodes. The 1st section briefly introduces the Ajax technology, the 2nd section describes the technical implementation process of the solution in detail, and the 3rd section analyzes the efficiency of the solution.

1. Ajax Overview

Jesse James Garnett, the earliest author of Ajax, believes that AJAX is not a new language or technology, it is actually a combination of several technologies in a certain way to play their respective roles in a common collaboration, including:

· Standardized presentation using extended hypertext markup language (XHTML) and Cascading Style Sheet (CSS;

· Use the Document Object Model (DOM) for Dynamic Display and interaction;

· Exchange and process data using the Extensible Markup Language (XML) and Extensible Stylesheet Language Transformation (XSLT;

· Use the XMLHTTP component XMLHTTPRequest object for asynchronous data reading;

· Finally, use JavaScript to bind and process all data.

As shown in Ajax's working principle 1, it is equivalent to adding an intermediate layer between the user and the server, making user operations asynchronous with the server response. Not all user requests are submitted to the server, for example, some data verification and data processing are handed over to the Ajax engine for processing, the Ajax engine submits requests to the server only when it is determined that new data needs to be read from the server. In this way, some server workload is transferred to the client, and the idle processing capability of the client is used to handle the workload of the server and bandwidth, this saves ISP space and bandwidth rental costs.


Figure 1 Comparison Between Web applications without Ajax (A) and Ajax (B)

2. Overall Design Scheme

Traditional server programs use the Model 1 development model. Generally, the business logic, server processing process, and HTML code are expressed together to quickly complete application development. Model 1 has obvious advantages in small-scale application development, but the application implementation is generally based on the process. A group of Server Pages implement a process. If the process changes, it will lead to modifications in multiple places, it is not conducive to application expansion and updates. In addition, the business logic and presentation logic are mixed in the server page, which is tightly coupled and cannot be modularized, leading to code reuse.

Model 2 solves these problems. It is an application of the object-oriented MVC model (Model-View-controller, Model-View-Controller) in Web development, model indicates the business logic of the application. view is the presentation page of the application, and Controller provides Process Control for the application. Through this MVC design pattern, application logic, processing process and display logic are divided into different components and modules for implementation, and components can be interacted and reused.

This solution adopts a J2EE multi-layer architecture. The presentation layer, business logic layer, and data layer are divided into different modules in combination with the Struts framework. The presentation layer focuses on the appearance and display of the tree. The business logic layer is the server-side processing program that processes the generation and changes of the tree. To reduce coupling, the program is all modularized, the model layer is the storage and representation of data. The implementation of each layer is described below.

2.1 presentation layer implementation

Similar to the folder mode of Windows resource manager, the node image style is shown in table 1. The DHTML code of each node must contain the node location, leading image, style, and other operations on the node. At the same time, some leading images are required to ensure node display consistency.

Table 1 image style table before a tree node

A division container is used for non-leaf nodes, images, and node information of the tree. Div and other containers are the basis of DHTML. You can use the script program to perform operations on its attributes, such as setting the display attribute of Its Style to control the expansion and hiding of subnodes. The node location, leading image, style, and other operations on the node are put into the container, for example:
<Div id = mparentid>

Computer School </div>

Leaf nodes can be output directly without containers.

When you click the "+" and "-" Images in front of a node, control the expansion and hiding of the subnode through the display attribute of the Style of the div. Display: "NONE" (hidden, invisible), display: "Block" (displayed ). The related JavaScript code is as follows:
If (expandchild. style. Display = "NONE ″){
// The current status is hidden. Execute the show action.
This. loading (parentobject); // determines whether the data of this branch has been loaded.
Expandchild. style. Display = "Block ″;
If (para2 = "last ″)
Parentobject. src = "lminus. GIF"; // The Last node.
Else
Parentobject. src = "tminus. GIF"; // The response is displayed.
Expandfolder. src = "folderopen. GIF ″;
} Else {
// Hide all the subnodes 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 tree Table Structure Design

We use the database as the carrier to record node changes. The tree table structure must have at least the following fields: the node number (classid), the description of the node (classname ), the ID of the parent node (parentid), which is required for building the tree structure. At the same time, introduce the class code of the node, the level of the node (classlevel), whether the secondary fields such as the leaf node (terminated), and record the node order, as shown in Entity Relationship Diagram 3.


Figure 3 tree table structure
The time complexity of tree traversal is O ( N), But after the tree information is stored in the database, you cannot traverse the tree in the traditional way. You must use SQL statements to access the content of the database table, and the more data you get at a time, the more resources the user consumes, the longer the user waits. If unordered data is read from the database, the sorted tree must be sent to the client for display on the server side. Therefore, it is best to read the sorted tree from the database.

We know that string sorting is in Lexicographic Order. In combination with the features and tree structure of SQL statements, in database tables, the node Category Code adopts the multi-level string format, such as aaabbbccc. Each level of string increases by one level from the root node, the sub-node category code starts with the parent node category code, and then starts the class code at this level. Nodes of the same level are numbered according to the generated sequence, for example, the codes of the next level of children whose node category code is AAA are aaaaaa and aaaaabaab, and the children whose aaaaaaab class code is aaaaaaabaaa and aaaaaaabaab. The width of each level-1 character is associated with the actual application, such as AAA ~ At the ZZZ level, there are 263 nodes. If it is not enough, add another character for encoding. This clever numbering method. After the SQL statement select * From tree_class order by classcode is executed, a complete FIFO tree is obtained at a time.

 

2.3 business logic layer design

2.3.1 dynamic loading technology

If you obtain the complete first-order tree at a time and construct it into XML for JavaScript parsing, the larger the data volume, the more resources consumed, and the longer the client response latency, therefore, for trees with large data volumes, the dynamic loading method is used, that is, each time you click the "+" image, you can determine whether the data of the subnode has been loaded, if the request is not loaded, the XMLHTTPRequest object of the XMLHTTP component of Ajax sends a request asynchronously, and connects to the server to execute the SQL statement "select * From tree_class where parent =? Order by classcode "to obtain node data. The related JavaScript code is as follows:
/* Determine whether data has been loaded. If data is not loaded, access the server to load data */

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 ();
/* Use the get method to asynchronously connect to the URL to load data */
This. xmldoc. Open ("get", URL, true); // true: asynchronous; false: Synchronous
This. xmldoc. Send (null );
} Catch (e ){
This. xmldoc = new activexobject ("Microsoft. XMLHTTP"); // use IE
This. xmldoc. Open ("get", URL, true); // true: asynchronous; false: Synchronous
This. xmldoc. Send (null );
}
Return this. xmldoc. responsexml;
}

Each time, only the subnode sequence of the same parent node parentid is obtained, and the document structure of the tree is encapsulated in XML format. For example:
<Tree id = "0">
<Leaf child = "1" name = "" id = "1" im0 = "leaf.gif" im1 = "folderopen.gif" IM2 = "folderclosed.gif"/>
</Tree>

Dhtmltreeobject provided to JavaScript. prototype. insertitem () parses and organizes HTML output nodes. Child: 1 indicates a subnode, 0 indicates no subnode, and im0 indicates an icon when no subnode exists; im1 indicates the icon when a subnode is enabled and IM2 indicates the icon when a subnode is disabled. Therefore, you can also customize the icon when constructing XML.

2.3.2 Tree Structure

The returned data from the database is an ordered first-order tree, while XML is a complete tree-structure document. Therefore, to construct tree data into a predefined XML format, you only need to start from the root node, traverse the tree to generate all the trees. The related JavaScript code is as follows:
/* Construct a dynamic loading tree */

Dtmlxmlobject. Prototype. constructtree = function (){

// Parse tree data using XML data obtained during dynamic loading

VaR node = This. xmlloader. getxmltopnode ("Tree ");

VaR parentid = node. getattribute ("ID ");

For (VAR I = 0; I <node. childnodes. length; I ++) {// parse the leaf nodes of XML files one by one

If (node. childnodes [I]. nodetype = 1) & (node. childnodes [I]. tagname = "leaf ")){
VaR name = node. childnodes [I]. getattribute ("text ");
............
VaR temp = dhtmlobject. a0find (parentid); // obtain the parent node object
Temp. xmlload = 1; // loaded
// Construct an HTML output Node
Dhtmlobject. insertitem (parentid, CID, name, im0, im1, IM2, CHD );
Dhtmlobject. adddragger = This; // you can drag and drop objects.
};
}

2.3.3 Tree Structure Maintenance

It is relatively simple to delete a node when maintaining a tree structure table. The SQL statement is: "delete from tree_class where classcode like '" + classcode + "% ′", you can delete the node along with the child node. When adding a node, the node can be divided into three situations: Forward insertion, backward insertion, and subnode insertion. The first two cases require updating the recursive update class code, the latter only needs to find the parent node's child's largest class code plus 1, as the class code to add nodes; when you drag and drop to change the tree structure, you only need to update the parentid of the dragged node to the classid of the target node. The corresponding SQL statement is: "Update tree_class set parentid =" + classidto + "where classid =" + classidfrom.

3. Efficiency Analysis

There are two types of tree storage: two types of tables and a linked list. The Traversal method also includes two types: Deep traversal and wide traversal. the time complexity of traversal is O (N). When using the orders table for storage, you can use the array marker in the memory to accurately locate the parent node of the node and the array subscript of the sibling node. The positioning of nodes in the database is also accurate, but when you read node information from the database to the memory, if you cannot locate node information through the memory array subscript, you must traverse it to find a node,NThe time for finding a node is O (N/2 ),NThe time complexity of node sorting will be O (N2/2), which is also the reason for the low efficiency of the tree structure in the B/S mode. This scheme uses the lexicographically numbered scheme, so that the tree obtained from the database is sorted and the client page program is directly traversed. the time complexity is O (N).

4. Conclusion

This article discusses the implementation scheme of Ajax-based dynamic tree structure, supports node information of the tree without refreshing, supports drag-and-drop nodes to change the node Structure and order of the tree, and uses the database to store node information, this solution ensures a certain degree of universality. In addition, combined with the node information of the XML Description tree, any information described in the XML document predefined in this solution can be displayed through the tree. This solution has been applied to the digital welcome system of our school and the General pharmacy information system.

 

 

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.