ztree 增删递归

package cn.com.shdmt.web.contorller;

import cn.com.shdmt.BizConstants;
import cn.com.shdmt.entity.ProductEntity;
import cn.com.shdmt.entity.ProductTypeEntity;
import cn.com.shdmt.framework.util.Constants;
import cn.com.shdmt.service.ProductService;
import cn.com.shdmt.service.ProductTypeService;
import cn.com.shdmt.web.vo.ProductTypeVo;
import cn.com.shdmt.web.vo.ZtreeVo;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.collect.Lists;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.mapper.JsonMapper;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yaoyao on 2015/1/26.
 */
@Controller
@RequestMapping(value = "/productType")
public class ProductTypeController {

    private static final String PAGE_SIZE = "10";
    private Logger logger = LoggerFactory.getLogger(ProductTypeController.class);

    //当点击其他业务的时候 显示分类列表   有分类的id  标记他的父节点是 其他业务
    //当点击分类id名称 显示业务列表
    //如果没有父节点则显示直接显示 只可以选择叶子节点 不是父节点的都是叶子节点

    @Autowired
    private ProductTypeService productTypeService;
    @Autowired
    private ProductService productService;

    @Value("#{appProperties[‘upload.config.uploadURL‘]}")
    private String uploadURL;
    @Value("#{appProperties[‘upload.config.fileURLPrefix‘]}")
    private String fileURLPrefix;

    @RequestMapping(method = RequestMethod.GET)
    public String list(
            @RequestParam(value = "page", defaultValue = "1") int pageNumber,
            @RequestParam(value = "order", defaultValue = "") String order,
            @RequestParam(value = "page.size", defaultValue = PAGE_SIZE) int pageSize,
            Model model) {
        /*Page<ProductTypeEntity> page = productTypeService.getAllProductType(new PageRequest(pageNumber - 1, pageSize), ViewParamsConvertUtils.getOrder(order));
        if (!StringUtils.isBlank(order)) {
            model.addAttribute("order", order);
        }
        model.addAttribute("page", page);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("fileURLPrefix", fileURLPrefix);*/

        return "productType/productType_list";
    }

    @RequestMapping(value = "doAjax")
    @ResponseBody
    public String doAjax() {

        List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByIsDeleted(Boolean.FALSE);
        List<ZtreeVo> ztreeVos = new ArrayList<ZtreeVo>();
        ZtreeVo zTree = new ZtreeVo();
        zTree.setId(0);
        zTree.setpId(-1);
        zTree.setName("服务分类管理");
        ztreeVos.add(zTree);

        for (ProductTypeEntity p : productTypeEntities) {
            ZtreeVo ztreeVo = new ZtreeVo();
            ztreeVo.setIsParent(!p.getIsLeaf());
            ztreeVo.setId(p.getId().intValue());
            ztreeVo.setpId(p.getParentId());
            ztreeVo.setName(p.getProductTypeName());
            ztreeVos.add(ztreeVo);
        }
        String json = new JsonMapper(JsonInclude.Include.ALWAYS).toJson(ztreeVos);
        return json;
    }

    @RequestMapping(value = "getproductById")
    @ResponseBody
    public ProductTypeVo getproductById(
            @RequestParam(value = "id", required = false) Long id
    ) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        ProductTypeVo productTypeVo = new ProductTypeVo();
        productTypeVo.setProductType(productTypeEntity.getProductType());
        productTypeVo.setProductTypeName(productTypeEntity.getProductTypeName());
        productTypeVo.setDescription(productTypeEntity.getDescription());
        productTypeVo.setImageUrl(fileURLPrefix + productTypeEntity.getImageUrl());
        return productTypeVo;
    }

    @RequestMapping(value = "delById")
    @ResponseBody
    public Map delById(
            @RequestParam(value = "id", required = false) Long id,
            @RequestParam(value = "isParent", required = false) Boolean isParent
    ) {
        //如果是父节点  则删除他的所有子节点
        //如果是子节点  找到他的父节点  查看他的子节点数目是否大于1  如果不大于1 则把他的父节点变成子节点

        Map map = new HashMap();
        try {

            if (isParent) {
                DecimalToBinary(new Integer(id.intValue()));
                ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
                productTypeEntity.setIsDeleted(Boolean.TRUE);
                productTypeService.save(productTypeEntity);
            } else {

                ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
                //得到当前节点的父节点的id
                Integer parentId = productTypeEntity.getParentId();
                List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByParentIdAndIsDeleted(parentId, Boolean.FALSE);
                System.out.println(productTypeEntities.size());
                if (productTypeEntities.size() <= 1) {
                    productTypeEntity.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(productTypeEntity);
                    ProductTypeEntity productTypeEntity1 = productTypeService.getProductType(Long.valueOf(parentId));
                    productTypeEntity1.setIsLeaf(Boolean.TRUE);
                    productTypeService.save(productTypeEntity1);
                }else{
                    productTypeEntity.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(productTypeEntity);
                }
            }

        } catch (Exception e) {
            logger.error("删除失败" + e);
            map.put("fail", "删除失败");
        }
        map.put("suc", "删除成功");
        return map;
    }

    public void DecimalToBinary(Integer id) {
        if (id == -1) {        //当num=0时,循环结束
            return;
        } else {
//            ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
            //找到该节点的子节点  保存该节点子节点的id 循环调用

            List<ProductTypeEntity> productTypeEntities = productTypeService.findAllByParentId(id);

            //如果有子节点 删除并记录子节点
            if (!productTypeEntities.isEmpty()) {

                for (ProductTypeEntity p1 : productTypeEntities) {
                    p1.setIsDeleted(Boolean.TRUE);
                    productTypeService.save(p1);
                }
                Integer parentId = new Integer(productTypeEntities.get(0).getId().intValue());
                DecimalToBinary(parentId);
            }
            id = -1;
        }
    }

    @RequestMapping(value = "update/{id}", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Long id, Model model) {
        model.addAttribute("productType", productTypeService.getProductType(id));
        model.addAttribute("action", "update");
        return "productType/productType_edit";
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String createForm(Model model) {
        ProductTypeEntity productType = new ProductTypeEntity();
        productType.setSortNo(0);
        model.addAttribute("productType", productType);
        model.addAttribute("action", "create");
        return "productType/productType_edit";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(@Valid ProductTypeEntity newProduct,
                         @RequestParam(value = "id", required = false) Long id,
                         @RequestParam(value = "isParent", required = false) Boolean isParent,
                         @RequestParam(value = "productTypeImageFile", required = false) MultipartFile productTypeImageFile,
                         RedirectAttributes redirectAttributes, HttpSession session) {
        String idStr = Constants.EMPTY_STRING;
        String filePath = null;
        //如果是父节点  则单纯添加一个子节点 他的父节点id 为treenode.id
        //如果是子节点treenode.id改为父节点 并且添加一个子节点他的父节点id为treenode.id
        if (productTypeImageFile != null && !productTypeImageFile.isEmpty()) {
            filePath = upload(productTypeImageFile, redirectAttributes, session);
        }
        if (id == null) {
            try {
                if (!isParent) {
                    ProductTypeEntity productTypeEntity = productTypeService.getProductType(Long.valueOf(newProduct.getParentId()));
                    productTypeEntity.setIsLeaf(Boolean.FALSE);
                    productTypeService.save(productTypeEntity);
                }
                newProduct.setImageUrl(filePath);
                newProduct.setIsLeaf(Boolean.TRUE);
                productTypeService.save(newProduct);
                redirectAttributes.addFlashAttribute("message", "创建服务类型成功");
            } catch (Exception e) {
                logger.error("创建服务类型失败", e);
                redirectAttributes.addFlashAttribute("error", "创建服务类型失败");
            }
        } else {
            ProductTypeEntity productTypeEntity = null;
            try {
                productTypeEntity = productTypeService.getProductType(id);
                productTypeEntity.setDescription(newProduct.getDescription());
                productTypeEntity.setProductType(newProduct.getProductType());
                productTypeEntity.setProductTypeName(newProduct.getProductTypeName());
                productTypeEntity.setImageUrl(filePath);
                productTypeService.save(productTypeEntity);
                idStr = productTypeEntity.getId().toString();
                redirectAttributes.addFlashAttribute("message", "更新服务类型【" + productTypeEntity.getProductTypeName() + "】成功");
            } catch (Exception e) {
                logger.error("更新服务类型失败", e);
                redirectAttributes.addFlashAttribute("error", "更新服务类型{" + productTypeEntity.getProductTypeName() + "}失败");
            }
        }
        return "redirect:/productType/" + idStr;
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("productType") ProductTypeEntity productTypeEntity,
                         @RequestParam(value = "productTypeImageFile", required = false) MultipartFile productTypeImageFile,
                         RedirectAttributes redirectAttributes, HttpSession session) {
        String idStr = Constants.EMPTY_STRING;
        try {

            String filePath = null;
            if (productTypeImageFile != null && !productTypeImageFile.isEmpty()) {
                filePath = upload(productTypeImageFile, redirectAttributes, session);
            }
            productTypeEntity.setImageUrl(filePath);
            productTypeService.save(productTypeEntity);
            idStr = productTypeEntity.getId().toString();
            redirectAttributes.addFlashAttribute("message", "更新服务类型【" + productTypeEntity.getProductTypeName() + "】成功");
        } catch (Exception e) {
            logger.error("更新服务类型失败", e);
            redirectAttributes.addFlashAttribute("error", "更新服务类型{" + productTypeEntity.getProductTypeName() + "}失败");
        }
        return "redirect:/productType/" + idStr;
    }

    //上传文件
    private String upload(MultipartFile knowledgeFile, RedirectAttributes redirectAttributes, HttpSession session) {
        String filePath = null;
        try {
            // 保存文件
            String fileName = knowledgeFile.getOriginalFilename();
            if (StringUtils.isNotBlank(fileName) && !knowledgeFile.isEmpty()) {
                //生成转发URL
                String url = uploadURL;
                //保存到本地
                File tempFile = new File(System.getProperty("java.io.tmpdir") + "/" + session.getId() +
                        fileName.substring(fileName.lastIndexOf(‘.‘)).toLowerCase());
                FileUtils.writeByteArrayToFile(tempFile, knowledgeFile.getBytes());
                //读取图片
                RestTemplate rest = new RestTemplate();
                FileSystemResource resource = new FileSystemResource(tempFile);

                MultiValueMap<String, Object> param = new LinkedMultiValueMap<String, Object>();
                //文件
                param.add("file", resource);
                //验证字符串
                param.add("validateString", BizConstants.UPLOAD_FILE_VALIDATE_STRING);
                //模块名,用于生成模块目录
                param.add("modeName", "link");
                //可选参数 fileType 文件类型,用于验证文件类型list,小写,默认{".jpg","png","gif"}
                //             fileMaxSize 文件大小上限Long,默认80000
                Map<String, String> message = rest.postForObject(url, param, Map.class);
                //删除临时文件
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                if (message.containsKey("error")) {
                    redirectAttributes.addFlashAttribute("message", message.get("error"));
                }
                filePath = message.get("filePath");
            }
        } catch (Exception ex) {
            logger.error("获取图片路径失败", ex);
        }
        return filePath;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String info(@PathVariable("id") long id, Model model) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        model.addAttribute("productType", productTypeEntity);
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        return "productType/productType_info";
    }

    @RequestMapping(value = "delete/{id}")
    public String delete(@PathVariable("id") Long id, Model model, RedirectAttributes redirectAttributes) {
        ProductTypeEntity productTypeEntity = productTypeService.getProductType(id);
        //如果服务分类下有服务  提示不能删除
        List<ProductEntity> productEntities = productService.findByProductTypeAndIsDeleted(productTypeEntity,Boolean.FALSE);
        if (productEntities.size() > 0) {
            redirectAttributes.addFlashAttribute("error", "删除服务类型" + productTypeEntity.getProductTypeName() + "失败,该服务类型下存在未删除的服务");
            return "redirect:/productType";
        }
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        productTypeEntity.setIsDeleted(Boolean.TRUE);//true 1 删除
        productTypeService.save(productTypeEntity);
        redirectAttributes.addFlashAttribute("message", "删除服务类型" + productTypeEntity.getProductTypeName() + "成功");
        return "redirect:/productType";
    }

    @RequestMapping(value = "batchDel")
    public String delete(@RequestParam(value = "productTypeId", required = false) Long[] productTypeId,
                         Model model, RedirectAttributes redirectAttributes) {
        List<String> stringList = Lists.newArrayList();
        if (productTypeId != null && productTypeId.length > 0) {
            List<ProductTypeEntity> productTypeEntities = productTypeService.getProductTypes(productTypeId);
            for (ProductTypeEntity productTypeEntity : productTypeEntities) {
                List<ProductEntity> productEntities = productService.findByProductTypeAndIsDeleted(productTypeEntity,Boolean.FALSE);
                if (productEntities.size() > 0) {
                    //存在预约单的  保留名字 提示客户哪些失败了
                    stringList.add(productTypeEntity.getProductTypeName());
                } else {
                    productTypeEntity.setIsDeleted(Boolean.TRUE);//true 1 删除
                    productTypeService.save(productTypeEntity);
                }
            }
        }
        if (stringList != null && stringList.size() > 0) {
            redirectAttributes.addFlashAttribute("error", "删除服务类型" + org.springframework.util.StringUtils.collectionToDelimitedString(stringList, ",") + "失败,该服务类型下存在未删除的服务,其他勾选成功删除");
        } else {
            redirectAttributes.addFlashAttribute("message", "删除服务类型成功");
        }
        model.addAttribute("fileURLPrefix", fileURLPrefix);
        return "redirect:/productType";
    }

    @ModelAttribute
    public void getProduct(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
        if (id != -1) {
            model.addAttribute("productType", productTypeService.getProductType(id));
        }
    }
}

jsp:

<%@ page contentType="text/html;charset=UTF-8" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="form" uri="http://www.springside.org.cn/tags/form" %><%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %><c:set var="ctx" value="${pageContext.request.contextPath}"/><html><head>    <title>服务分类维护</title>    <link href="${ctx}/static/zTree/css/zTreeStyle/zTreeStyle.css" media="screen" rel="stylesheet"/>    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.core-3.5.min.js"></script>    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.excheck-3.5.min.js"></script>    <script type="text/javascript" src="${ctx}/static/zTree/js/jquery.ztree.exedit-3.5.js"></script>    <style>

        .addLeaf {            border: 1px solid #DDD;            background-color: #F5F5F5;            color: #ACA899;        }

    </style></head><body>

<%--<div  id="activation_city_list" class="ztree"></div><input type="hidden" name="cityIds" id="cityIds"/>--%>

[ <a id="addLeaf" href="#" title="增加节点" onclick="return false;">增加服务分类</a> ][ <a id="edit" href="#" title="编辑节点" onclick="return false;">编辑服务分类</a> ][ <a id="info" href="#" title="查看节点" onclick="return false;">查看服务分类</a> ][ <a id="del" href="#" title="删除节点" onclick="return false;">删除服务分类</a> ]

<div style="float:left;">    <ul id="treeDemo" class="ztree">    </ul></div>

<!-- 模态框(Modal) --><div class="modal hide fade" id="modelSave" tabindex="-1" role="dialog"     aria-labelledby="myModalLabel" aria-hidden="true">    <div class="modal-dialog">        <div class="modal-content">            <div class="modal-header">                <button type="button" class="close"                        data-dismiss="modal" aria-hidden="true">                    &times;                </button>                <h4 class="modal-title">                    添加                </h4>            </div>            <div class="modal-body" style="max-height: 350px;">                <%--=======--%>                <div class="well">                    <form:form id="edit_custom_form" modelAttribute="productType" action="${ctx}/productType/create"                               method="post"                               enctype="multipart/form-data" class="form-horizontal">                        <input type="hidden" name="id" id="id"/>                        <input type="hidden" id="pid" name="parentId">                        <input type="hidden" id="isParent" name="isParent">                        <fieldset>

                            <div class="ui-state-default">                                <b>基本信息</b>                            </div>                            <div class="well well-small">

                                <div class="control-group">                                    <label for="productType" class="control-label">服务分类编号:</label>

                                    <div class="controls">                                        <input id="productType" style="width: 200px" name="productType" type="number"                                               maxlength="20" class="input-large required"/>                                        <span style="color: red">*</span>                                    </div>                                </div>

                                <div class="control-group">                                    <label for="productTypeName" class="control-label">服务分类名称:</label>

                                    <div class="controls">                                        <input id="productTypeName" style="width: 200px" name="productTypeName"                                               type="text"                                               maxlength="20" class="input-large required"/>                                        <span style="color: red">*</span>                                    </div>                                </div>

                                <div class="control-group">                                    <label for="productTypeImage" class="control-label">服务分类图片:</label>

                                    <div class="controls">                                        <input type="file" id="productTypeImage" name="productTypeImageFile"                                               class="input-large"/>                                        <span style="color: red">*</span>                                    </div>                                </div>

                                <div class="control-group">                                    <label for="description" class="control-label">服务分类描述:</label>

                                    <div class="controls">                                        <input id="description" style="width: 200px" name="description" type="text"                                               maxlength="20" class="input-large required"/>                                        <span style="color: red">*</span>                                    </div>                                </div>

                                <div class="form-actions">                                    <input class="btn btn-primary" style="width: 80px;float: left" type="submit"                                           value="提交"/>                                </div>                            </div>                        </fieldset>                    </form:form>                </div>

                <%--=======--%>

            </div>        </div>        <!-- /.modal-content -->    </div>    <!-- /.modal --></div>

<!-- 模态框(Modal) --><%--查看--%><div class="modal hide fade" id="modelInfo" tabindex="-1" role="dialog"     aria-labelledby="myModalLabel" aria-hidden="true">    <div class="modal-dialog">        <div class="modal-content">            <div class="modal-header">                <button type="button" class="close"                        data-dismiss="modal" aria-hidden="true">                    &times;                </button>                <h4 class="modal-title">                    查看                </h4>            </div>            <div class="modal-body" style="max-height: 350px;">                <%--=======--%>

                <div class="well">                    <div class="ui-state-default">                        <b>基本信息</b>                    </div>                    <table class="well table">

                        <tr>                            <th>                                服务分类编号:                            </th>                            <td id="info_productType">                            </td>                        </tr>

                        <tr>                            <th>                                服务分类名称:                            </th>                            <td id="info_productTypeName">                            </td>                        </tr>

                        <tr>                            <th>                                服务分类图片:                            </th>                            <td id="info_imageUrl">

                            </td>                        </tr>

                        <tr>                            <th>                                服务分类描述:                            </th>                            <td id="info_description">                            </td>                        </tr>

                    </table>                </div>

                <%--=======--%>

            </div>        </div>        <!-- /.modal-content -->    </div>    <!-- /.modal --></div>

<script>

//==

var setting = {    view: {        selectedMulti: false        //禁止多点选中    },    data: {        simpleData: {            enable: true,            idKey: "id",            pIdKey: "pId",            rootPId: ""        }    },    callback: {        onRename: onRename,//编辑后触发,用于操作后台        beforeDrag: beforeDrag,        beforeRemove: beforeRemove,        beforeRename: beforeRename,        onClick: zTreeOnClick    }};

function zTreeOnClick(event, treeId, treeNode) {    if (treeNode.isParent) {        //如果是父节点//        $("#addLeaf").removeClass("addLeaf");        $("#edit").addClass("addLeaf");        $("#info").addClass("addLeaf");//        $("#del").addClass("addLeaf");    } else {//        $("#addLeaf").addClass("addLeaf");        $("#edit").removeClass("addLeaf");        $("#info").removeClass("addLeaf");//        $("#del").removeClass("addLeaf");    }};

var log, className = "dark";function beforeDrag(treeId, treeNodes) {    return false;}function beforeRemove(treeId, treeNode) {    className = (className === "dark" ? "" : "dark");    showLog("[ " + getTime() + " beforeRemove ] " + treeNode.name);    return confirm("确认删除 节点 -- " + treeNode.name + " 吗?");}function onRemove(e, treeId, treeNode) {    showLog("[ " + getTime() + " onRemove ] " + treeNode.name);}function beforeRename(treeId, treeNode, newName) {    if (newName.length == 0) {        alert("节点名称不能为空.");        var zTree = $.fn.zTree.getZTreeObj("treeDemo");        setTimeout(function () {            zTree.editName(treeNode)        }, 10);        return false;    }    return true;}function showLog(str) {    if (!log) log = $("#log");    log.append("<li class=‘" + className + "‘>" + str + "</li>");    if (log.children("li").length > 8) {        log.get(0).removeChild(log.children("li")[0]);    }}function getTime() {    var now = new Date(),            h = now.getHours(),            m = now.getMinutes(),            s = now.getSeconds(),            ms = now.getMilliseconds();    return (h + ":" + m + ":" + s + " " + ms);}

var newCount = 1;

function add(e) {    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),            isParent = e.data.isParent,            nodes = zTree.getSelectedNodes(),            treeNode = nodes[0];    if (typeof(treeNode) != "undefined") {        if (treeNode.isParent) {            $("#pid").val(treeNode.id);//拿到父节点的id填写名称后保存 重新加载            $("#isParent").val(treeNode.isParent);            $("#id").val("");            $("#productType").val("");            $("#productTypeName").val("");            $("#description").val("");            //当点击添加的时候弹出框            $("#modelSave").modal(‘show‘);            onloadZTree();        } else {            //当前选中的节点   treeNode.id  变成父节点 并添加一个他的子节点            $("#pid").val(treeNode.id);//拿到父节点的id填写名称后保存 重新加载            $("#id").val("");            $("#isParent").val(treeNode.isParent);            $("#productType").val("");            $("#productTypeName").val("");            $("#description").val("");            //当点击添加的时候弹出框            $("#modelSave").modal(‘show‘);

        }    } else {

    }};

function info(e) {    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),            isParent = e.data.isParent,            nodes = zTree.getSelectedNodes(),            treeNode = nodes[0];    if (typeof(treeNode) != "undefined") {

        if (treeNode.isParent) {

        } else {            //根据id 进行 ajax            var data = {id: treeNode.id};            $.ajax({                cache: false, //是否使用缓存                type: ‘post‘, //请求方式,post                data: data,                dataType: "json", //数据传输格式                url: "${ctx}/productType/getproductById", //请求链接                error: function () {                    alert(‘加载出错!‘);                },                success: function (data) {                    if (data != null) {                        $("#info_productType").text(data.productType);                        $("#info_productTypeName").text(data.productTypeName);                        $("#info_imageUrl").html("<img src=‘${fileURLPrefix}" + data.imageUrl + "‘ style=‘width: 66; height: 56px;‘>");                        $("#info_description").text(data.description);                        $("#modelInfo").modal(‘show‘);                    } else {                        alert("加载出错");                    }                }            });        }    } else {

    }}

function edit(e) {

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),            isParent = e.data.isParent,            nodes = zTree.getSelectedNodes(),            treeNode = nodes[0];    if (typeof(treeNode) != "undefined") {

        if (!treeNode.isParent) {

            //根据id 进行 ajax            var data = {id: treeNode.id};            $.ajax({                cache: false, //是否使用缓存                type: ‘post‘, //请求方式,post                data: data,                dataType: "json", //数据传输格式                url: "${ctx}/productType/getproductById", //请求链接                error: function () {                    alert(‘加载出错!‘);                },                success: function (data) {                    if (data != null) {                        $("#id").val(treeNode.id);                        $("#productType").val(data.productType);                        $("#productTypeName").val(data.productTypeName);                        $("#description").val(data.description);                        $("#modelSave").modal(‘show‘);                    } else {                        alert("加载出错");                    }                }            });        }    }

}

function del(e) {

    var zTree = $.fn.zTree.getZTreeObj("treeDemo"),            isParent = e.data.isParent,            nodes = zTree.getSelectedNodes(),            treeNode = nodes[0];    if (typeof(treeNode) != "undefined") {           var data;        if (!treeNode.isParent) {            //根据id 进行 ajax            data = {id: treeNode.id, isParent: treeNode.isParent};        } else {            data = {id: treeNode.id, isParent: treeNode.isParent};        }

        $.ajax({            cache: false, //是否使用缓存            type: ‘post‘, //请求方式,post            data: data,            dataType: "json", //数据传输格式            url: "${ctx}/productType/delById", //请求链接            success: function (data) {                if (data["suc"] != null) {                    alert(data["suc"]);                    onloadZTree();                } else {                    alert(data["fail"]);                }            }        });    }}

function onRename(e, treeId, treeNode, isCancel) {    //当编辑完成后    return treeNode.name;}

//用于捕获分类编辑名称结束(Input 失去焦点 或 按下 Enter 键)之后,更新分类名称数据之前的事件回调函数function beforeRename(treeId, treeNode, newName) {    if (newName.length == 0 || newName.indexOf("请输入名称") >= 0) {        alert(‘亲,请输入分类名称!‘);        var zTree = $.fn.zTree.getZTreeObj("treeDemo");        setTimeout(function () {            zTree.editName(treeNode)        }, 10);        return false;    }    if (newName.length > 15) {        alert(‘亲,分类名称过长!‘);        var zTree = $.fn.zTree.getZTreeObj("treeDemo");        setTimeout(function () {            zTree.editName(treeNode)        }, 10);        return false;    }    native_name = treeNode.name;    return true;};

//加载ztreefunction onloadZTree() {    var ztreeNodes;    $.ajax({        async: true, //是否异步        cache: false, //是否使用缓存        type: ‘post‘, //请求方式,post        dataType: "json", //数据传输格式        url: "${ctx}/productType/doAjax", //请求链接        error: function () {            alert(‘网络出错!‘);        },        success: function (data) {            ztreeNodes = data; //将string类型转换成json对象            var treeObj = $.fn.zTree.init($("#treeDemo"), setting, ztreeNodes);            treeObj.expandAll(true);            zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");        }    });}

//初始化操作$(document).ready(function () {    onloadZTree();    $("#addLeaf").bind("click", {isParent: false}, add);    $("#info").bind("click", {isParent: false}, info);    $("#edit").bind("click", {isParent: false}, edit);    $("#del").bind("click", {isParent: false}, del);});

</script>

<%--<tags:pagination page="${page}" paginationSize="${pageSize}"/>--%></body></html>
时间: 2024-10-25 14:16:04

ztree 增删递归的相关文章

关于树如laytree,ztree节点数据的组装(递归实现)

在一些项目中需要用到树形结构来表示一些层级关系时候,可用如在layui框架中的laytree或者ztree来完成效果如图 往往在获取节点数值时候所需要的数据的结构比较复杂,比如laytree和ztree的节点数据结构都是如图所示,即数组 下有children元素,然后里面又是一样的结构循环下去 大概的需求就是上面这样,在实际项目中设计好数据库如下结构 然后通过后台获取数据,组成所需的数组返回到前台,代码在下面,看完注释正常来说已经清楚了(*^__^*) 嘻嘻 public function le

Java递归获取部门树 返回ztree数据

@GetMapping("/getDept")@ResponseBodypublic Tree<DeptDO> getDept(String deptId){ Tree<DeptDO> deptNode = getDeptNode(deptId); if (deptNode == null){ return null; } List<Tree<DeptDO>> childNode = getChildNode(deptId); for (

zTree

js树形控件—zTree使用总结 0 zTree简介 树形控件的使用是应用开发过程中必不可少的.zTree 是一个依靠 jQuery 实现的多功能 “树插件”.优异的性能.灵活的配置.多种功能的组合是 zTree 最大优点. 0.0 zTree的特点 最新版的zTree将核心代码按照功能进行了分割,不需要的代码可以不用加载,如普通使用只需要加载核心的jquery.ztree.core-3.5.js,需要使用勾选功能加载jquery.ztree.excheck-3.5.min.js,需要使用编辑功

Python基础之内置函数和递归

本文和大家分享的主要是python中内置函数和递归相关内容,一起来看看吧,希望对大家学习python有所帮助. 一.内置函数 下面简单介绍几个: 1.abs() 求绝对值 2.all() 如果 iterable 的所有元素都为真(或者如果可迭代为空),则返回  True 3.any() 如果 iterable 的任何元素为真,则返回  True .如果iterable为空,则返回  False 4.callable() 如果  object 参数出现可调,则返回  True ,否则返回  Fal

(菜鸟要飞系列)四,基于Asp.Net MVC5的后台管理系统(zTree绑定Json数据生成树)

上一次老师让我们用递归将中国城市镇县四级联动 显示在树上,那个时候就知道可以显示在zTree上,可是苦于对Json的不了解,对zTree的Api的不了解,一直没有做出来,只好将递归算法显示在了窗体上,见C# 使用winForm的TreeView显示中国城镇四级联动, 前几天老师终于将他以前做的zTree的例子给我研究,终于知道了怎么写了(哭瞎,好没有成就感),感觉网上这部分资源好少,有也是关于SqlServer用EntityFramework中数据上下文写的,由于老师不让用EntityFrame

通过Ztree生成页面html元素Dom树,以及拖拽改变元素的位置

zTree 是一款依靠 jQuery 实现的多功能 "树插件",http://www.treejs.cn/v3/main.php#_zTreeInfo,功能强大,不多赘述. 下面我将介绍如何实现使用该插件生成HTML元素Dom树,并对其进行多样操作. 先贴上一个简单的HTML页面(直接拿的ztree的用的,画面简单实用,里面的文字内容不用在意) 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-e

zTree的getChangeCheckedNodes()使用心得以及一次性获取zTree的所有节点

zTree的getChangeCheckedNodes()方法用于获取输入框勾选状态被改变的节点集合.如果需要获取每次操作后全部被改变勾选状态的节点数据,请在每次勾选操作后,遍历所有被改变勾选状态的节点数据,让其 checkedOld = checked 就可以了. 问题一:checkedOld是什么?仔细查看api会发现“treeNode 节点数据详解”模块有一个叫作checkedOld的excheck扩展属性,表示节点的 checkBox / radio 在初始化时的勾选状态.[settin

ztree设置节点checked

1.根据id获取树的某个节点: var zTree = $.fn.zTree.getZTreeObj("mytree"); var node = zTree.getNodeByParam("id",1); 2.设置node节点选中状态: zTree.selectNode(node); 3.设置node节点checked选中,有两种方法实现: (1).zTree.checkNode(node, true, true); (2).node.checked = true;

递归实现EasyUI中Tree的Json格式

最近在做学校的基础系统的时候前台需要树形的组织结构,由于前台的整体框架都用的是EasyUI,所以只能采用EasyUi中Tree的格式,可是麻烦的是,需要符合EasyUI中Tree的Json格式,我们先看一下,格式是如何的呢? <span style="font-size:18px;">[{ "id":1, "text":"My Documents", "children":[{ "id