ZTree development drop-down tree and ztree development drop-down tree

Source: Internet
Author: User
Tags tojson

ZTree development drop-down tree and ztree development drop-down tree

Recently, because the work requires a tree-like drop-down box component, there are two methods to query data. One is to use zTree; the other is to use easyUI. Because the company's front-end is not designed using easyUI, I chose zTree to implement the drop-down tree.

Here, the simple data format (that is, the simple Json format) is similar to the following Json:

Var zNodes = [{id: 1, pId: 0, name: "Beijing"}, {id: 2, pId: 0, name: "Tianjin"}, {id: 3, pId: 0, name: "Shanghai" },{ id: 6, pId: 0, name: "Chongqing" },{ id: 4, pId: 0, name: "Hebei Province", open: true, nocheck: true}, {id: 41, pId: 4, name: "Shijiazhuang" },{ id: 42, pId: 4, name: "Baoding" },{ id: 43, pId: 4, name: "Handan" },{ id: 44, pId: 4, name: "Chengde" },{ id: 5, pId: 0, name: "Guangdong Province", open: true, nocheck: true}, {id: 51, pId: 5, name: "Guangzhou"}, {id: 52, pId: 5, name: "Shenzhen" },{ id: 53, pId: 5, name: "Dongguan" },{ id: 54, pId: 5, name: "Foshan"}, {id: 6, pId: 0, name: "Fujian Province", open: true, nocheck: true}, {id: 61, pId: 6, name: "Fuzhou" },{ id: 62, pId: 6, name: "Xiamen" },{ id: 63, pId: 6, name: "Quanzhou" },{ id: 64, pId: 6, name: "Sanming"}];

Here, we first need an Entity bean to encapsulate the corresponding data, as shown below:

Public class ZtreeNode {// id private String id; // parent id private String pId; // display name private String name; // whether to enable this function (this function is disabled by default, if you want to enable it, set it to true) // private boolean open; // whether to select (set whether the node can be selected by default, and if it is set to true, the node cannot be selected) // private boolean nocheck;/** getter and setter */}

 Note that the second letter in the pId is in upper case. If it is written in lower case, it cannot be constructed into a tree structure, and all are root nodes.

Then, convert the data from the database to the bean required by the corresponding ztree and then to the corresponding Json. The Code is as follows:

// Returns the json public String getGoodsCategoryTreeJson () {List <GoodsCategory> allGoodsCategoryList = goodsCategoryService. topology (); List <ZtreeNode> ztreelist = new ArrayList <ZtreeNode> (); for (GoodsCategory gcty: topology) {ZtreeNode treenade = new ZtreeNode (); treenade. setId (gcty. getId (); treenade. setpId (gcty. getParent () = null? "": Gcty. getParent (). getId (); treenade. setName (gcty. getName (); ztreelist. add (treenade);} return ajax (ztreelist );}

Convert list to the corresponding Json method as follows:

Json toolkit used:

import org.springframework.base.util.JsonUtil;
Private static final String HEADER_ENCODING = "UTF-8"; private static final boolean HEADER_NO_CACHE = true; private static final String HEADER_TEXT_CONTENT_TYPE = "text/plain "; private static final String HEADER_JSON_CONTENT_TYPE = "text/plain"; // AJAX outputs protected String ajax (String content, String contentType) {try {HttpServletResponse response = initResponse (contentType); response. getWriter (). write (content); response. getWriter (). flush ();} catch (IOException e) {e. printStackTrace ();} return NONE;} // output AJAX protected String ajax (String text) {return ajax (text, HEADER_TEXT_CONTENT_TYPE) based on the text content );} // output AJAX protected String ajax (Status status) {HttpServletResponse response = initResponse (HEADER_JSON_CONTENT_TYPE); Map <String, String> jsonMap = new HashMap <String, string> (); jsonMap. put (STATUS_PARAMETER_NAME, status. toString (); JsonUtil. toJson (response, jsonMap); return NONE;} // outputs AJAX protected String ajax (Status status, String message) {HttpServletResponse response = initResponse (HEADER_JSON_CONTENT_TYPE) based on the Operation Status and message content ); map <String, String> jsonMap = new HashMap <String, String> (); jsonMap. put (STATUS_PARAMETER_NAME, status. toString (); jsonMap. put (MESSAGE_PARAMETER_NAME, message); JsonUtil. toJson (response, jsonMap); return NONE;} // output AJAX protected String ajax (Object object) {HttpServletResponse response = initResponse (HEADER_JSON_CONTENT_TYPE); JsonUtil Based on the Object. toJson (response, object); return NONE;} // output AJAX protected String ajax (boolean booleanStatus) {HttpServletResponse response = initResponse (HEADER_JSON_CONTENT_TYPE) according to the boolean state; Map <String, object> jsonMap = new HashMap <String, Object> (); jsonMap. put (STATUS_PARAMETER_NAME, booleanStatus); JsonUtil. toJson (response, jsonMap); return NONE;} private HttpServletResponse initResponse (String contentType) {HttpServletResponse response = ServletActionContext. getResponse (); response. setContentType (contentType + "; charset =" + HEADER_ENCODING); if (HEADER_NO_CACHE) {response. setDateHeader ("Expires", 1L); response. addHeader ("Pragma", "no-cache"); response. setHeader ("Cache-Control", "no-cache, no-store, max-age = 0");} return response ;}

In this way, the data required by the front-end is retrieved from the library and encapsulated into the corresponding Json.

The next step is the front-end implementation. The js and css to be imported at the front-end are as follows:

<link rel="stylesheet" href="${base}/template/ztree/css/demo.css" type="text/css"><link rel="stylesheet" href="${base}/template/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css"><script type="text/javascript" src="${base}/template/ztree/js/jquery.ztree.core.js"></script>

Here, only demo.css is customized, and all of them are official. demo.css modifies the css used in the official demo, as shown below (redundant styles are not deleted here );

 1 div.content_wrap {width: 400px;} 2 div.content_wrap div.left{float: left;} 3 div.content_wrap div.right{float: right;width: 340px;} 4 div.zTreeDemoBackground {text-align:left;} 5  6 ul.ztree {margin-top: 10px;border: 1px solid #617775;background: #fefefe;width:220px;height:360px;overflow-y:scroll;overflow-x:auto;} 7 ul.log {border: 1px solid #617775;background: #f0f6e4;width:300px;height:170px;overflow: hidden;} 8 ul.log.small {height:45px;} 9 ul.log li {color: #666666;list-style: none;padding-left: 10px;}10 ul.log li.dark {background-color: #E3E3E3;}11 12 /* ruler */13 div.ruler {height:20px; width:220px; background-color:#f0f6e4;border: 1px solid #333; margin-bottom: 5px; cursor: pointer}14 div.ruler div.cursor {height:20px; width:30px; background-color:#3C6E31; color:white; text-align: right; padding-right: 5px; cursor: pointer}

Then, it is the corresponding drop-down box:

 1 <div class="content_wrap"> 2     <div class="zTreeDemoBackground left"> 3          <input id="citySel"  class="formText" type="text" onclick="showMenu(); return false;" readonly value="" style="width:150px;"/> 4          <input id="treeids" type="hidden" name="goods.goodsCategory.id" > 5          <input type="button" onclick="showMenu();" value="∨"> 6     </div> 7 </div> 8<div id="menuContent" class="menuContent" style="display:none; position: absolute;"> 9    <ul id="treeDemo" class="ztree" style="margin-top:0;"></ul>10 </div>

There is a hidden text box to store the id of the selected content in the drop-down box.

The script is as follows:

<SCRIPT type = "text/javascript"> var setting = {view: {dblClickExpand: false}, data: {simpleData: {enable: true }}, callback: {onClick: onClick}, view :{
// The corresponding showIcon: false }}; function onClick (e, treeId, treeNode) {var zTree =$. fn. zTree. getZTreeObj ("treeDemo"), nodes = zTree. getSelectedNodes (), v = ""; ids = ""; nodes. sort (function compare (a, B) {return. id-b.id ;}); for (var I = 0, l = nodes. length; I <l; I ++) {v + = nodes [I]. name + ","; ids + = nodes [I]. id + ",";} if (v. length> 0) v = v. substring (0, v. length-1); var cityObj =$ ("# citySel "); CityObj. attr ("value", v); // place the selected id in the hidden text field if (ids. length> 0) ids = ids. substring (0, ids. length-1); var treeids =$ ("# treeids"); treeids. attr ("value", ids) ;}function showMenu () {var cityObj =$ ("# citySel"); var cityOffset =$ ("# citySel "). offset (); $ ("# menuContent" ).css ({left: cityOffset. left + "px", top: cityOffset. top + cityObj. outerHeight () + "px "}). slideDown ("fast"); $ ("body "). bind ("mous Edown ", onBodyDown);} function hideMenu () {$ (" # menuContent "). fadeOut ("fast"); $ ("body "). unbind ("mousedown", onBodyDown);} function onBodyDown (event) {if (! (Event.tar get. id = "menuBtn" | event.tar get. id = "menuContent" | token (event.tar get ). parents ("# menuContent "). length> 0) {hideMenu () ;}} var zNodes; $ (document ). ready (function () {// load data $. ajax ({async: false, cache: false, type: 'post', dataType: 'json', url: '$ {base}/admin/goods! GetGoodsCategoryTreeJson. action ', error: function () {alert ('request failed') ;}, success: function (data) {zNodes = data ;}}); $. fn. zTree. init ($ ("# treeDemo"), setting, zNodes) ;}); </SCRIPT>

In this way, a drop-down box is complete. As shown in:

If you need to write back the corresponding drop-down list data on the modify page, add the following script:

<script type="text/javascript">$(document).ready(function(){    if ("${goods.goodsCategory.id}"!="") {        var treeObj = $.fn.zTree.getZTreeObj("treeDemo");        var node = treeObj.getNodeByParam("id", "${goods.goodsCategory.id}" , null);        treeObj.selectNode(node,false , false);        onClick(event,"${goods.goodsCategory.id}",node,true);            }});</script>

 

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.