ajax异步请求数据,用bootstrap中的tree模板实现tree

来源:互联网 发布:地磅软件称重软件 编辑:程序博客网 时间:2024/05/22 12:15
后台数据格式json数据data:
{"0":[{"id":1,"fatherId":0,"typeName":"测试","typeIndex":0,"typeStatus":"1"}],
"1":[{"id":2,"fatherId":1,"typeName":"测试类别1","typeIndex":1,"typeStatus":"1"},{"id":3,"fatherId":1,"typeName":"测试类别2","typeIndex":2,"typeStatus":"1"},{"id":4,"fatherId":1,"typeName":"测试类别3","typeIndex":3,"typeStatus":"1"}],
"3":[{"id":5,"fatherId":3,"typeName":"测试类别4","typeIndex":4,"typeStatus":"1"},{"id":6,"fatherId":3,"typeName":"测试类别5","typeIndex":5,"typeStatus":"1"}]}
后台将数据按照key-value的形式存入map,key值为父id,value为同一父id的Po组成的List中,传入前台,方便构建类别树,其中data[0]为初始化的根,需要保证返回的数据按照层级的先后顺序。
前台处理:
前台页面添加一个 <ul role="tree" id="typeLiId0"></ul>容器,
执行以下js方法
function listTypeTree(id){    doPost("/action/type/listTypeTree",{},function(objs){        if(objs.success){            var data = objs.data;            if(null == data){                showErrorMsg("","类别信息失败!");                return;            }            var obj = $("#" + id + " > div");            for (var item in data) {                appendNodeToTree('typeLiId', data[item]);            }            bindEvent();        }else{        }    });}
/**追加节点*/
function appendNodeToTree(id, data){    for (var i = 0, l = data.length; i < l; i++) {        $("#" + id + data[i].fatherId).append('<li data-content="'+data[i].id+'"><span><i class="icon-leaf"></i>'+data[i].typeName+'</span><ul id="typeLiId'+data[i].id+'"></ul></li>');    }}
/**从bootstrap-tree.js拷贝*/function bindEvent(){    $('.tree > ul').attr('role', 'tree').find('ul').attr('role', 'group');    $('.tree').find('li:has(ul)').addClass('parent_li').attr('role', 'treeitem').find(' > span').attr('title', 'Collapse this branch').on('click', function (e) {        var children = $(this).parent('li.parent_li').find(' > ul > li');        if (children.is(':visible')) {            children.hide('fast');            $(this).attr('title', 'Expand this branch').find(' > i').addClass('icon-plus-sign').removeClass('icon-minus-sign');        }        else {            children.show('fast');            $(this).attr('title', 'Collapse this branch').find(' > i').addClass('icon-minus-sign').removeClass('icon-plus-sign');        }        e.stopPropagation();    });}


1 0