頁面代碼:
<div id="MenuTree"></div>
javascript代碼:
$(document).ready(function ($) { InitMenuTree(); }); function InitMenuTree() { $('#MenuTree').data('jstree', false); $.getJSON('@Url.Action("GetMenuTree", "AdminMenu")', function (json) { $('#MenuTree').jstree({ 'core': { 'data': json } }); }); $('#MenuTree').on('changed.jstree',function (node,data){ var id = data.instance.get_node(data.selected[0]).id;//節點點擊事件 獲取ID ClickMenuTree(id); }) $('#MenuTree').on('loaded.jstree', function (e, data) { data.instance.open_all();//默認展開所有節點 }) }
使用jQuery的getJson方法從后台獲取數據,然后直接放到data后面就行了。
后台代碼:
Models:(這是jstree要求的格式)
public class AdminMenuTreeNoteModel { public string id { get; set; } public string parent { get; set; } public string text { get; set; } public string icon { get; set; } }
Controllers:(我用的是.Net MVC 這不重要,直接把數據按照規定的JSON格式傳出去就行了)
public ActionResult GetMenuTree() { var trees = from a in dbc.AdminMenus select new AdminMenuTreeNoteModel { id = a.ID.ToString(), parent = (a.ParentMenu > 0 ? a.ParentMenu.ToString() : "#"),//默認根節點的parent是“#” text = a.Title, icon = (a.IconClass.Length > 0 ? a.IconClass : "icon-doc")//部分節設定好了圖標,沒有圖標的使用默認圖標 }; return Json(trees.ToList(), JsonRequestBehavior.AllowGet); }
完事,還是很簡單的。但是JsTree的官方網站里的文檔根本看不懂。
這里是規定的JSON格式:
// Alternative format of the node (id & parent are required) { id : "string" // required parent : "string" // required text : "string" // node text icon : "string" // string for custom state : { opened : boolean // is the node open disabled : boolean // is the node disabled selected : boolean // is the node selected }, li_attr : {} // attributes for the generated LI node a_attr : {} // attributes for the generated A node }
UPDATE:
后來初始化樹代碼改成這樣了:
function InitMenuTree() { $('#MenuTree').on('changed.jstree',function (node,data){ var id = data.instance.get_node(data.selected[0]).id;//獲取ID ClickMenuTree(id); FromStateShow(); }) $('#MenuTree').on('loaded.jstree', function (e, data) { data.instance.open_all();//默認展開所有節點 }) GetMenuTreeData(); } function GetMenuTreeData() { $('#MenuTree').data('jstree', false); $.ajax({ url: '@Url.Action("GetMenuTree", "AdminMenu")', type: 'post', dataType: 'json' }) .done(function(data) { $('#MenuTree').data('jstree', false).empty().jstree({ 'core': { 'data': data } }); }); }
這樣可以直接調用 GetMenuTreeData() 刷新樹了。
我發現 $.getJSON() 可能有緩存,反正還用 $.getJSON 修改后沒有辦法刷新樹內容。
如果只是顯示出來不需要刷新的話就無所謂,需要刷新還得換一個方法。