Project structure :

Project presentations :

Technical points :

1.3.2 Technical points
In the introduction of the basic principle , Learn that by dynamically creating child nodes within the parent node , And use the style sheet indent to complete the tree list
Basic framework . Apart from that , There are also some issues to consider .
1 . Put all the children of the parent node into a container
The basic principle page only contains the function of creating child nodes , You can't close the created node again . The practical application
The menu always contains open and close operations . For the convenience of closing , Put the child node in a container , When closed
Just set the display properties of the container .
2 . The realization of node switch
After all the children of each parent node are put into the container , Judge the display state of the child node container when you click the parent node . If at present
For open state , Turn it off , Otherwise, turn it on . The specific method is to call the node style.display Attribute to judge ,
The state of closing is none, Not none Time means open . To clearly represent the open or closed state of the parent node , Use “+” and
“-” Characters to identify .
3 . Nodes are divided into directory nodes and non directory nodes
The directory node can contain child nodes , Non directory nodes are also called leaf nodes , That is, the node does not contain child nodes . In this case
These two kinds of nodes are treated differently . Click a directory node to expand or close its children . Clicking on a non directory node will link
Go to a new page ( For now, pop up the new page address , It can be modified in practical application ).

database :

/*
SQLyog Ultimate v12.09 (64 bit)
MySQL - 5.5.53 : Database - ajaxexample_3
*********************************************************************
*/ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`ajaxexample_3` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `ajaxexample_3`; /*Table structure for table `tree` */ DROP TABLE IF EXISTS `tree`; CREATE TABLE `tree` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT ' Primary key ',
`text` varchar(255) NOT NULL COMMENT ' Show text ',
`isfolder` varchar(5) NOT NULL DEFAULT 'false' COMMENT ' Whether there is a lower level directory ',
`link` varchar(255) NOT NULL COMMENT ' Connect ',
`pid` int(11) NOT NULL DEFAULT '0' COMMENT ' Father id',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; /*Data for the table `tree` */ insert into `tree`(`id`,`text`,`isfolder`,`link`,`pid`) values (1,' Catalog 1','true','',0),(2,' Catalog 2','true','',0),(3,' Catalog 3','true','',0),(4,' Catalog 1-1','true','',1),(5,' Catalog 1-2','true','',1),(6,' Catalog 1-3','true','',1),(7,' Catalog 2-1','true','',2),(8,' project 1','false','https://www.baidu.com',2),(9,' project 1','false','https://www.baidu.com',0),(10,' project 2','false','https://www.baidu.com',0); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

GetTreeByParentId.java: Get node information servlet:

package com.gordon.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException; import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.gordon.util.DBUtils; /**
* Servlet implementation class GetTreeByParentId
*/
@WebServlet("/GetTreeByParentId")
public class GetTreeByParentId extends HttpServlet {
private static final long serialVersionUID = 1L; /**
* @see HttpServlet#HttpServlet()
*/
public GetTreeByParentId() {
super();
// TODO Auto-generated constructor stub
} /**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setContentType("text/xml;charset=utf-8"); String parentId = request.getParameter("parentId"); // Get the node number to load
// Create to save xmlTree The information of StringBuffer object
StringBuffer xmlTree = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
xmlTree.append("<tree>"); // xmlTree The root node is <tree>
/*
* Different results are returned according to the target node of the request isFolder Property to identify whether the current node is a directory ,true Presentation directory ,false Represents a normal node link
* Property is used to set the destination link address of a normal node
*/
String sql = "select * from tree where pid = ?"; // Define the SQL sentence
Connection conn = null; // Statement Connection object
PreparedStatement pstmt = null; // Statement PreparedStatement object
ResultSet rs = null; // Statement ResultSet object
try {
conn = DBUtils.getConnection(); // Get database connection
pstmt = conn.prepareStatement(sql); // establish PreparedStatement
pstmt.setString(1, parentId); // Set parameters
rs = pstmt.executeQuery(); // Execute the query , Return result set
while (rs.next()) { // Traverse the result set to create item node
xmlTree.append("<item id=\"");
xmlTree.append(rs.getString("id"));
xmlTree.append("\" isFolder=\"");
xmlTree.append(rs.getString("isfolder"));
String link = rs.getString("link");
// When link Field data is added when it exists link Attribute information
if (link != null && !"".equals(link)) {
xmlTree.append("\" link=\"");
xmlTree.append(link);
}
xmlTree.append("\">");
xmlTree.append(rs.getString("text"));
xmlTree.append("</item>");
}
} catch (ClassNotFoundException cnfe) {
System.out.println(cnfe.toString());
} catch (SQLException e) {
System.out.println(e.toString());
} try {
rs.close(); // Close result set
pstmt.close(); // close PreparedStatement
conn.close(); // Close the connection
} catch (Exception e) {
System.out.println(e.toString());
} xmlTree.append("</tree>"); // xmlTree The end tag of the root node System.out.println(xmlTree.toString()); response.getWriter().print(xmlTree.toString());
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
} }

DBUtil.java: Database connection :

package com.gordon.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException; public class DBUtils {
private static final String URL = "jdbc:mysql://localhost:3306/ajaxexample_3";
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USERNAME = "root";
private static final String PASSWORD = "root"; public static Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName(DRIVER);
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}

tree.css:

/* Child node container box Need to indent */
div.box {
margin-left: 20px;
}
/* Directory node identification style */
span.folderMark {
font-family: " Song style ";
color: #F00;
cursor: hand;
margin-right: 5px;
}
/* Directory node style */
span.folder {
cursor: hand;
}
/* Non directory node identification style */
span.itemMark {
font-family: " Song style ";
color: #F00;
margin-right: 5px;
}
/* Non directory node styles */
span.item {
cursor: hand;
}

tree.js:

// establish Tree object 
var Tree = new function() {
this._url = "GetTreeByParentId"; // The server page address used to request data this._openMark = "-"; // The identity of the directory node when it is in the expanded state
this._closeMark = "+"; // The identity of the directory node when it is down
this._itemMark = "·"; // Non directory node identification this._initId = "treeInit"; // Tree initial div identification
this._rootData = " root directory "; // Root node text message this._boxSuffix = "_childrenBox"; // Child node container suffix this._folderType = "folder"; // Directory node type variable
this._itemType = "item"; // Non directory node type variables // Initialize root
this.init = function() {
var initNode = document.getElementById(this._initId); // Get the initial div
var _node = document.createElement("div"); // Create a new div As root node _node.id = "0"; // The root node id by 0
_node.innerHTML = this.createItemHTML(_node.id, this._folderType,
this._rootData);
initNode.appendChild(_node); // Add the root node to the initial div
} // Gets the child nodes of a given node
this.getChildren = function(_parentId) {
// Get page sub node container box
var childBox = document.getElementById(_parentId + this._boxSuffix);
// If the child node container already exists , Set the display state directly , Otherwise, get the child node information from the server
if (childBox) {
var isHidden = (childBox.style.display == "none"); // Determine whether the current state is hidden
// Hidden shows , If it is displayed, it becomes hidden
childBox.style.display = isHidden ? "" : "none";
// Modify the parent node ID according to the display status of the child node
var _parentNode = document.getElementById(_parentId);
_parentNode.firstChild.innerHTML = isHidden ? this._openMark
: this._closeMark;
} else {
var xmlHttp = this.createXmlHttp(); // establish XmlHttpRequest object
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
// call addChildren Function to generate child nodes
Tree.addChildren(_parentId, xmlHttp.responseXML);
}
}
xmlHttp.open("GET", this._url + "?parentId=" + _parentId, true);
xmlHttp.send(null);
}
} // According to the xmlTree Information , Set the children of the specified node
this.addChildren = function(_parentId, _data) {
var _parentNode = document.getElementById(_parentId); // Get parent node
_parentNode.firstChild.innerHTML = this._openMark;// Mark the node as a directory expansion before setting it
// Create a container , be called box, It is used to store all the child nodes
var _nodeBox = document.createElement("div");
// Container of id The rule is : On the parent node id Add a fixed suffix after
_nodeBox.id = _parentId + this._boxSuffix;
_nodeBox.className = "box"; // The style name is box,div.box The style takes effect on this node
_parentNode.appendChild(_nodeBox); // Put the child nodes box Put in the parent node
// Get all item node
var _children = _data.getElementsByTagName("tree")[0].childNodes; var _child = null; // Statement _child Variables are used to hold each child node
var _childType = null; // Statement _childType Variables are used to hold each child node type
for (var i = 0; i < _children.length; i++) { // Loop to create each child node
_child = _children[i];
_node = document.createElement("div"); // Each node corresponds to a new div
_node.id = _child.getAttribute("id"); // Node id The value is to get the id Property value
// Set the child node type
_childType = _child.getAttribute("isFolder") == "true" ? this._folderType
: this._itemType;
// Depending on the node type , call createItemHTML Create node content
if (_childType == this._itemType) {
// The non directory node transmits one more at the end link data , Used to click and link to a new page
_node.innerHTML = this.createItemHTML(_node.id, _childType,
_child.firstChild.data, _child.getAttribute("link"));
} else {
// The directory node just needs to pass id, Node type , Node data
_node.innerHTML = this.createItemHTML(_node.id, _childType,
_child.firstChild.data);
}
_nodeBox.appendChild(_node); // Add the created node to the child node box in
}
} // Create a page fragment of the node
this.createItemHTML = function(itemId, itemType, itemData, itemLink) {
// Depending on the node type , Return to a different HTML fragment
if (itemType == this._itemType) {
// Non directory node class Attribute to item start , also onclick Event call Tree.clickItem function
return '<span class="itemMark">' + this._itemMark + '</span>'
+ '<span class="item" onclick="Tree.clickItem(\''
+ itemLink + '\');">' + itemData + '</span>';
} else if (itemType == this._folderType) {
// Directory node class Attribute to folder start , also onclick Event call Tree.getChildren function
return '<span class="folderMark" onclick="Tree.getChildren(\''
+ itemId + '\')">' + this._closeMark + '</span>'
+ '<span class="folder" onclick="Tree.getChildren(\''
+ itemId + '\')">' + itemData + '</span>'
}
} // Actions after clicking the leaf node , For now, it's just a dialog box , Can be modified to link to a specific page
this.clickItem = function(_link) {
alert(" The current node can be linked to the page " + _link + " .");
} // Used to create XMLHttpRequest object
this.createXmlHttp = function() {
var xmlHttp = null;
// according to window.XMLHttpRequest Whether objects exist or not, using different creation methods
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest(); // FireFox、Opera And so on
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); // IE How to create browser support
}
return xmlHttp;
}
}

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title> Dynamic tree list </title>
<script type="text/javascript" src="js/tree.js"></script>
<link href="css/tree.css" type="text/css" rel="stylesheet">
</head>
<body onload="Tree.init()">
<h1> Dynamic tree list </h1>
<div id="treeInit"></div>
</body>
</html>

+++++++++++++++++++++++++++

Reference resources :ajax Practical cases -1 Load data dynamically  https://wenku.baidu.com/view/c7897bf4700abb68a982fb91.html

Ajax-ajax example 3- More articles on dynamic tree list

  1. Winform Development of the main interface menu dynamic tree list display

    I've written many articles before , Introduced Winform The development of the main interface , It's basically a standard interface , Place the toolbar at the top , The middle area holds the contents of multiple documents , But when there are more menus at the top , You need to divide the menu into several levels , For example, you can put a ...

  2. PHP+Ajax Click to load more list data instances

    A simple and practical PHP+Ajax Click to load more list data instances , Realization principle : adopt “ more ” Button to send Ajax request ,PHP Query the latest records according to paging parameters , The data to JSON returns , The front desk Query analysis JSON Count ...

  3. js Chinese vs arry Summary of various operations of array The waterfall flow AJAX No refresh to load data list -- When the page scrolls to Id And then continue loading the data web front end url Transfer value js Encryption and decryption HTML Let the form input Text box is read-only and cannot be edited js Monitor the user's keystroke events , Compatible with major mainstream browsers HTML Special characters

    js Chinese vs arry Summary of various operations of array   Recently, the work is relatively easy , So I took the time to do it from beginning to end js Have carried on the detailed study and the review , In the process of reading , I found that in the process of doing the project, I couldn't think about it completely , It's not reasonable , So say ...

  4. AJAX Database instance

    AJAX For creating more dynamic applications . AJAX ASP example The following example demonstrates when a user types characters in an input box , How a web page communicates with a server : example Please type the letter in the input box below (A - Z): full name : Suggest ...

  5. ajax Common example code summary, novice to reference ( One )

    http There are four ways to interact :get.post.put( Add data ).delete( Delete data ) put and delete It's implemented with get and post   get The way The page cannot be modified , Just get the query information . But the number of submissions ...

  6. AJAX XML example

    AJAX XML example The following example demonstrates how to use the web page AJAX To read from XML File information <!DOCTYPE html> <html> <head> < ...

  7. php in ajax Using examples

    php in ajax Using examples One . summary 1. Review more : These two pieces of code are very simple , Just need to review , See more 2.ajax principle :ajax It's just a partial update of the page , It's still there html After the page listens to the event , And then pass it to the server for operation , here ...

  8. thinkphp in ajax Using examples (thinkphp Built in support ajax)

    thinkphp in ajax Using examples (thinkphp Built in support ajax) One . summary 1.thinkphp It should be built-in support ajax Of , So the request type will have whether it is ajax // Is it Ajax request if ...

  9. jquery The solution of style invalidation after adding list dynamically

    I'm making an address book recently , Use jquery mobile The way to do , After adding the list dynamically ,listview The original style is invalid , For a while , Find a solution . The code is as follows . <%@ page language=" ...

Random recommendation

  1. Java Learning essays 1:Java Value passing or reference passing ?

    Java always passes arguments by value NOT by reference. Let me explain this through an example: publ ...

  2. IIS 7.5 To configure 10W High concurrency

    original text :    http://www.myhack58.com/Article/sort099/sort0100/2012/35585.htm original text :   http://www.myhack58.com ...

  3. Radiobutton edit

    package com.example.yuekao3; import java.util.ArrayList;import java.util.List; import com.baidu.farm ...

  4. MYSQL Don't order

    mysql: SELECT * FROM EVENT WHERE eventId IN(443,419,431,440,420,414,509) ORDER BY INSTR(',443,419,43 ...

  5. Stage3D_Game_Programming: Rendering 3D Model

    OBJ It's a document , Let's explain first OBJ file . Look for any one OBJ file , View with text : ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 # ...

  6. Google is a must HTML/CSS standard

    background This article defines HTML and CSS Format and code specification of , Designed to improve code quality and collaboration efficiency . Generic style specifications agreement Omit the picture . style . Scripts and other media files URL Part of the agreement ( http:,https: ) ...

  7. Gitlab Manage the local Git To configure

    The company's project team uses Gitlab, Members of the group are assigned a fixed git Personal account , Different members have different module editing permissions , You need to configure the local Git. Yes, always use svn For a small dish , This can only be used with a little step configuration . with ...

  8. HDU 4622 Reincarnation( Postfix automaton )

    [ Topic link ] http://acm.hdu.edu.cn/showproblem.php?pid=4622 [ The main idea of the topic ] Give a length not exceeding 2000 String , Not more than 10000 A asked , ask [L,R] Substring ...

  9. 95 Post intern telecommuting experience (asp.net mvc\C# Technology stack )

    This month we did something that other people seem crazy about , That is to let a batch of 95 Interns after the implementation of telecommuting , It's not bad , So write this article to summarize . In fact, seriously calculate , I have ten years of teleworking experience myself , When working in Beijing, I applied to work at home when the weather was bad , ...

  10. Windows install Scoop

    Scoop Introduce scoop yes Windows Package management tools under Installation environment requirements 1, Operating environment :win10 2, Make sure your  PowerShell edition >= 3. win7 Maybe less than 3, We have to upgrade . How to confirm Pow ...