Extended a jquery tree plug-in simpletree and added the asynchronous loading capability of JSON format data.

Source: Internet
Author: User

Reprinted: http://www.javaeye.com/topic/249851

Since learning to use jquery, I have never found a simple tree that supports asynchronous loading, but I have to extend it myself. The Treeview function of jquery's official UI is single and not small enough. The simpletree plug-in finds that it is small and supports drag-and-drop extension. Therefore, based on simpletree, The JSON format data is asynchronously loaded and the image path used in the tree is elastically expanded. This is rough. Please give us some advice!

 

In actual projects, the following example is based on struts2. In addition to the struts2 environment, the Struts-JSON plug-in jsonplugin is also required, to directly use servlet, you only need to use the static method in jsonlib to convert Java list to a JSON string.

 

Tree initialization method after modification

JS Code
  1. $ (Document). Ready (function (){
  2. Simpletreecollection = $ ('# simpletree'). simpletree ({
  3. Autoclose: True,
  4. Animate: True,
  5. Datatype: "JSON ",
  6. URL: "tree! Demotest. Action"
  7. });
  8. });
$(document).ready(function(){simpleTreeCollection = $('#simpleTree').simpleTree({autoclose: true,animate:true,dataType:"json",url:"tree!demoTest.action"});});

HTML code
  1. <Body>
  2. <UlId = "simpletree" class = "simpletree">
  3. </Ul>
  4. </Body>
<body> <ul id="simpleTree" class="simpleTree"></ul></body>

 

Code of the default options of the modified initialization tree

JS Code
TREE.option = {drag:true,animate:false,autoclose:false,speed:'fast',afterAjax:false,afterMove:false,afterClick:false,afterDblClick:false,// added by Erik Dohmen (2BinBusiness.nl) to make context menu cliks availableafterContextMenu:false,docToFolderConvert:false,//***added by Bluespring to enable json dataType***dataType:"json", //value is json or htmlasync:true,jsonWrap:{//if your dataType of json differ from following default type,you can wrap itid:"id",//node idparentId:"parentId",//parent node idtext:"text",//node textisfolder:"isfolder",//indication node whether or not folder, value is true or false,if not need, set it to null for nothing to doattrs:"attrs"//addition data for special action to customize function,if not need, set it to null for nothing to do},url:null, //if null,will use simple tree default setting. if not null,simpleTree defalut setting will be coverparm:{},//parameters for ajax request, always add or overwrite a key/value(key:jsonWrap.id,value:folder id) when expand folderresponseDataName:"nodes",//if your java nodeList name differ from "nodes", set it as your nodeList nametreeName:"tree"};

 

E is not easy to comment out, please don't mind. The jsonwrap option in the Code is a converter. With this option, we do not have to encapsulate the list of specific objects in the background for transmission, only objects in the returned list have attributes corresponding to ID, parentid, and text. Of course, if the custom functions on your interface require additional data, you must encapsulate the list of the following objects in the background.

Java code
Package util. tree. bean; import Java. util. arraylist; import Java. util. hashmap; import Java. util. list; public class simpletreenode {private Object ID; private string text; private object parentid;/*** is only used for folder nodes that require Asynchronous Data Reading. This attribute does not work when a node has a subnode. The node is always a folder node */private Boolean isfolder = false; private hashmap <string, Object> attrs = new hashmap <string, Object> (); Public simpletreenode (Object ID, string text, object parentid) {This. id = ID; this. TEXT = text; this. parentid = parentid;} public simpletreenode (Object ID, string text, object parentid, Boolean isfolder) {This. id = ID; this. TEXT = text; this. parentid = parentid; this. isfolder = isfolder;} public simpletreenode (Object ID, string text, object parentid, Boolean isfolder, hashmap <string, Object> attrs) {This. id = ID; this. TEXT = text; this. parentid = parentid; this. isfolder = isfolder; this. attrs = attrs;} public void addattribute (string key, object Value) {This. attrs. put (Key, value);} public object GETID () {return ID;} public void setid (Object ID) {This. id = ID;} Public String gettext () {return text;} public void settext (string text) {This. TEXT = text;} public object getparentid () {return parentid;} public void setparentid (Object parentid) {This. parentid = parentid;} public Boolean isfolder () {return isfolder;} public void setfolder (Boolean isfolder) {This. isfolder = isfolder;} public hashmap <string, Object> getattrs () {return attrs;} public void setattrs (hashmap <string, Object> attrs) {This. attrs = attrs ;}}

 

JS end uses asynchronous data to generate tree Node Code

JS Code
//***added by Bluespring for auto imgPath***//get js pathvar jsPath = "";            var js = $("script[src]").get();            for (var i = js.length; i > 0; i--) {                if (js[i - 1].src.indexOf("tree.js") > -1) {                    jsPath = js[i - 1].src.substring(0, js[i - 1].src.lastIndexOf("/") + 1);                }        }//***added by Bluespring to enable json dataType***var coverJsonToHtml=function(nodeArray){//create tree nodevar ul=$("<ul>");var nodeWrap=TREE.option.jsonWrap;var tempLi=null;for(var i in nodeArray){tempLi=$('<li id="'+nodeArray[i][nodeWrap.id]+'"><span>'+nodeArray[i][nodeWrap.text]+'</span></li>');if(nodeWrap.attrs!=null){tempLi.attr(nodeArray[i][nodeWrap.attrs]);}if(null!=nodeArray[i][nodeWrap.parentId]){tempLi.get(0).parentId=nodeArray[i][nodeWrap.parentId];tempLi.get(0).isFolder=nodeWrap.isFolder!=null?nodeArray[i][nodeWrap.isFolder]:false;}ul.append(tempLi);}//arrange tree nodevar parentLi=null;$("> li",ul).each(function(){if(this.parentId){parentLi=$("#"+$(this).attr("parentId"),ul);if($("ul",parentLi).size()==0){parentLi.append("<ul>");}$(this).appendTo($("ul",parentLi));}if(this.isFolder&&$("ul",this).size()==0){$(this).append("<ul>");}});$("ul",ul).each(function(){if($("li",this).size()==0){$(this).addClass("ajax");}});return ul;};

Attach the action class for testing and Struts Configuration

 

Java code
package org.wisdoor.web.util;import java.util.ArrayList;import java.util.List;import org.wisdoor.web.WisdoorAction;import util.tree.bean.SimpleTreeNode;public class TreeAction extends WisdoorAction {private List<SimpleTreeNode> nodes=new ArrayList();public String demoTest(){for(int i=0;i<10;i++){nodes.add(new SimpleTreeNode(""+i,"node_"+i,null,true));for(int n=0;n<5;n++){nodes.add(new SimpleTreeNode((""+i)+"_"+n,"node_"+i+"_"+n,""+i));}}return SUCCESS;}public List<SimpleTreeNode> getNodes() {return nodes;}public void setNodes(List<SimpleTreeNode> nodes) {this.nodes = nodes;}}

 

 

XML Code
  1. <! -- Tree -->
  2. <PackageName = "Tree" extends = "JSON-Default">
  3. <ActionName = "Tree" class = "org. wisdoor. Web. util. treeaction">
  4. <ResultType = "JSON">
  5. <ParamName = "ignorehierarchy">
  6. False
  7. </Param>
  8. </Result>
  9. </Action>
  10. </Package>

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.