jsTree通过AJAX从后台获取数据

时间:2023-03-08 23:38:34
jsTree通过AJAX从后台获取数据

页面代码:

<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 > ? a.ParentMenu.ToString() : "#"),//默认根节点的parent是“#”
text = a.Title,
icon = (a.IconClass.Length > ? 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[]).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 修改后没有办法刷新树内容。

如果只是显示出来不需要刷新的话就无所谓,需要刷新还得换一个方法。