Ztree dynamically loading the tree menu from the database

Source: Internet
Author: User

These days to do dynamic menu with the plug-in, the current use of a very wide open source framework, the latest release of the Qui framework is the use of this plugin development of the menu part, so it is well worth in-depth research and learning, through the use of sensory functions are rich, many functions do not develop and write their own, Official web site has a very detailed API can be consulted, using a handy but learning to use the process also encountered some difficulties, listening to repeated testing and check the data are understood, but also in the thinking of a problem, how to make the fastest time from contact with a new thing to the degree of flexibility to grasp?

This is not only a tree-shaped menu, each node can have a check box to the left, it is very simple to see, just need to configure a checked attribute in the setting.

The current experience feels that this is used in organizational structure, classification, and especially permissions, if done with this plugin will be perfectly integrated with your own business logic.

Principle is very easy to understand not too much to say its principle, roughly the same as the Ajax asynchronous request principle, look at the introduction you also understand that this framework is all asynchronous request data, improve the user experience.

Learning this process, I have the following points to waste a little time to come out and share with you, so that we can use the next project easier to get started.

static data and Dynamic Data

This framework supports XM, JSON and other data formats, we recommend that you use JSON format data to feel better, loading faster, about the data format can refer to the official website to some of the data, the official website above is a number of false data, if the dynamic generation menu indifferent need to be queried from the database, It is then converted into a JSON string, which needs to parse the JSON string itself.

In the previous project did not really do their own research on the parsing string, now used can only now learn to slow down the development efficiency, this should belong to the development of the foundation.

I myself try to write several methods to parse, try to refer to the method on the Internet, several iterations can not generate the correct string, the last one or parse out, from the database is a list of lists, and then parse him into a JSON string, all the data are displayed in the top-level menu, Check that the JSON string is the same as the given example, but it does not have a folding effect.

The original is not parsing JSON string is not correct, but it is printed to the interface is a first-level printing, not all look out all print out, so of course, in a level, which is also said static load all nodes, very disgusting JSON string, we strongly recommend that we have a number of several analytical JSON, Array and other methods of conversion, these are very basic ability, usually will be used frequently.

Isparent node

We all know that this node is not a parent node, what does it mean, in use when I send isparent to true, it means that the node to the left to accept a single-machine event, that is, there will be an expansion symbol, each Click will trigger an asynchronous commit data, request child node data loading on the page. Normally if you do not click on the parent node all child nodes are not loaded into the page.

Background spanning tree JSON string code

     Treelist=resourceservice.list (CHILDMAP);     Jsonarray jsonarray=new Jsonarray ();    for (Organization organization:treelist) {jsonobject jsonobject=new jsonobject ();    Jsonobject.put ("id", Organization.getid ());    Jsonobject.put ("pid", Organization.getpid ());        Jsonobject.put ("Name", Organization.getname ());     Determines whether the selected node is a parent node, if the Isparent property is set to True, is not set to False for Map subchildmap=new Linkedhashmap ();     Subchildmap.put ("Sqlid", "Subchildlst");    Subchildmap.put ("id", Organization.getid ());    List<organization> subtreelist=new arraylist<organization> ();    Subtreelist=resourceservice.list (SUBCHILDMAP);    if (subtreelist.size () > 0) {jsonobject.put ("Isparent", "true");    }else {jsonobject.put ("Isparent", "false");}    Boolean ischecked=resourceservice.ischecked (Contactid,organization.getid ()); if (Null==contactid | | ". Equals (ContactID) | |" Null ". Equals (ContactID)) {jsonobject.put (" checked "," false ");} else {if (isChecked) {jsonobject.Put ("Checked", "true");}        else {jsonobject.put ("checked", "false");}}    Jsonobject.put ("Open", "false");    Jsonarray.put (Jsonobject); }string Json=jsonutil.tojson (Jsonarray);


Checked node

The tree is a selected node, this node is also useful, such as loading a product it belongs to which classification, in the process of loading the tree, you want to load the default selected items, how do you want to implement it?

Dynamically load the default selected node, took half a day to figure out how to do, sometimes not we do not write code but no ideas, sometimes have ideas but not work at this time we need to change the angle of thinking, in programming also pay attention to thinking from a multi-angle, do not drill to a point up.

Resolve Dynamic Load Default Check I use the pass parameter, on the General page to pass the parameters feel very easy, I want to use this page is a popup page, Using the Window.Open property, the popup box dynamically load the menu and select the selected, Ztree from the official web API said is not able to pass parameters, there is a otherparm property can be said to accept only static parameters, is a key value pair, I added a JS function in value, through this function call The value of a variable on the parent form, the code is as follows;

<script type= "Text/javascript" >var setting = {check: {enable:true,chkstyle: "checkbox", Chkboxtype: {"Y": "", "N" : ""}},//get JSON data async: {enable:true, url: "Http://127.0.0.1:8080/contact/resource . Do?method=getztreenodes ",//Ajax Gets the URL address of the data autoparam: [" id "," name "],//ajax commit, pass the ID value of other        Param: ["ContactID", function () {return window.opener.document.getElementById ("ContactID"). Value; }]}, data:{//must use data simpledata: {enable:true, Idke          Y: "id",//ID number named PIdKey: "PId",///Parent ID number named rootid:0}},                  Callback function callback: {onclick:function (event, Treeid, TreeNode, Clickflag) {                                      if (true) {alert ("Node ID is:" + Treenode.id + ", the node text is:" + treenode.name);                           }   },//capture an asynchronous Load event callback function with an exception error and a successful callback function Onasyncsuccess:function (event, Treeid, TreeNode, msg) { Alert ("Call succeeded!")            ");            var nodes=getcheckednodes (true));            alert (nodes);  }, Beforeclick:beforeclick,oncheck:oncheck}}; function Beforeclick (Treeid, TreeNode) {var ztree = $.fn.ztree.getztreeobj ("Treedemo"); Ztree.checknode (TreeNode,!) Treenode.checked, NULL, TRUE); return false;} var code;function showcode (str) {if (!code) code = $ ("#code"); Code.empty (); Code.append ("<li>" +str+ "</li>" );} $ (document). Ready (function () {$.fn.ztree.init ($ ("#treeDemo"), setting);//setcheck ();}); function OnCheck (e,treeid,treenode) {var ztree = $.fn.ztree.getztreeobj ("Treedemo"), nodes = Ztree.getcheckednodes ( true), V = ""; var ids= ""; for (var i=0, l=nodes.length; i<l; i++) {v + = Nodes[i].name + ","; ids+=nodes[i].id+ ",";} if (ids.length > 0) ids = ids.substring (0, ids.length-1); alert (IDs); if (v.length > 0) v = v.substring (0, v.length-1); Cityobjids=window.opener.document.getelementbyid ("Cateselids"). Value=ids;                     Cityobjname=window.opener.document.getelementbyid ("Cateselname"). Value=v; } function GetSelectedNodes () {var ztree = $.fn.ztree.getztreeobj ("Treedemo"), nodes = Ztree.getcheckednodes (true), V = ""; var ids= ""; for (var i=0, l=nodes.length; i<l; i++) {v + = Nodes[i].name + ","; ids+=nodes[i].id+ ",";} if (ids.length > 0) ids = ids.substring (0, ids.length-1), alert (IDS), if (v.length > 0) v = v.substring (0, v.length- 1);//var cityobj = $ ("#citySel"),//var Cityobjids = $ ("#citySelIds");//Assign a value to the category that belongs to the parent form updatecontact.jsp Window.opener.document.getElementById ("Cateselids"). Value=ids;    Window.opener.document.getElementById ("Cateselname"). Value=v; }function Winclose () {window.close ();} </SCRIPT>
Run effect, dynamic drop-down list tree


In the work of others to explain the code or a little bit of detailed explanation is almost no, our manager only said you use that ztree to do the dynamic menu.

To be able to read someone's code as a programmer

Let me look at other people's code, I said look at the look I do not want to see, but also I write it myself, in fact, look at others code has always felt very boring, and now the idea changed some, others write code whether it is good or bad, we are worth looking at for reference, has been improving the class study did not see how people write code in the end, think accelerated people write code regardless of quality, style is the same

Comment More, empty line more, format specification, easy to read, this is like learning English, just listen to standard pitch is not, need to be very standard pitch also listen to dialect, so as to let our reading code of the ability to really improve.

As a programmer or developer there is an inappropriate place to take the initiative to solve and to optimize.

A few days ago encountered a problem, need to pass a parent node ID, to get all of his sub-node list or ID, in my code with stored procedures implemented, but the use of running more inefficient, the project manager let me optimize the optimization of the stored procedure can understand but do not know where to optimize, Find a search from the Internet find an algorithm to replace the query becomes faster.

Talk about the process of learning a new thing

Sometimes it takes a new thing to make you do something, a thing you haven't touched, and how we can learn and make the task as quickly as possible at this time.

      Think in the project, and sometimes can not even do hands-on but must think more, Instead of telling you how to do it , for the simplest example, what is the difference between a post submission and a get commit? An obscure question if you have not seriously thought, sometimes at some point you will encounter a small obstacle, think that with the solution of a mathematical problem, only the understanding of each knowledge point, can be associated with each other, to achieve a variety of knowledge integrated flexible use, the process of doing the project who can be handy, It is also easy to reach the highest level that teacher said.

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.