ajax非同步請求資料,用bootstrap中的tree模板實現tree
阿新 • • 發佈:2019-01-01
後臺資料格式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();
});
}