JSON 数据(JSON data)
使用 JSON 填充树
格式
jsTree 有一种约定的 JSON 格式。 在标准的语法中,没有任何字段是必须的,你可添加任意的字段。 你可访问任何你添加进去的字段,jsTree 不会修改你传入的数据, 因此你可在后续操作中访问原来的字段数据。
icon用于为节点设置图标,值是字符串。
-
字符串包含/,则认为是一个图片文件。
-
字符串不包含/,则认为是 CSS 的 class(<i>的类)。
-
false,则禁用节点图标。
state用于指定节点的状态,可使用下面选项的任意组合:opened selected disabled。
li_attr和a_attr都直接传递给 jQuery 的attr()函数。
当使用 AJAX 时,若children的值为布尔值true,则 jsTree 会将节点渲染为已关闭。 当用户点开此节点时,才会再次发起 AJAX 请求获取对应的数据。
任何嵌套的子节点,都应是
-
遵循相同的格式对象
-
或,普通字符串(此字符串用做节点名,其他的节点属性都自定生成)
// Expected format of the node (there are no required fields){ id : "string" // will be autogenerated if omitted 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 }, children : [] // array of strings or objects li_attr : {} // attributes for the generated LI node a_attr : {} // attributes for the generated A node}
可选的 JSON 格式
若不想使用嵌套children的方法,可使用另一个方法:
-
每个节点仅有id和parent字段
-
每个节点均没有children字段
jsTree 会自动解释继承关系。 若是根节点,则只需设置其parent字段为#。
此方法适用于一次性加载整棵树,或存储数据到数据库。
// 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}
使用 JSON
用 JSON 格式数据生成一棵树,需对$.jstree.defaults.core.data进行配置。
格式应是一个节点数组,每个节点都是一个对象或一个普通字符串(此时字符串仅作为节点名,其他节点属性将自动生成)。 任何嵌套的节点都应以相同的格式放在其父节点的children字段中。
$('#using_json').jstree({ 'core' : { 'data' : [ 'Simple root node', { 'text' : 'Root node 2', 'state' : { 'opened' : true, 'selected' : true }, 'children' : [ { 'text' : 'Child 1' }, 'Child 2' ] } ]} });
使用可选的 JSON 格式
$('#using_json_2').jstree({ 'core' : { 'data' : [ { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" }, { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" }, { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" }, { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" }, ]} });
使用 AJAX
可通过 AJAX 从服务器获取 JSON 数据来构建树。 JSON 格式如前面所述,唯一不同的是 JSON 不是来自配置对象,而是来自服务器。
可通过配置$.jstree.defaults.core.data来更好使用此功能。
只需使用类似 jQuery AJAX 的配置,jstree 即可自动发送 AJAX 请求来获取填充树的数据。
请在响应数据的每个LI中添加jstree-closed类,且不要在其中再嵌套UL, 因为 jstree 会自动发起另外的 AJAX 请求来请求嵌套的节点数据。
除了标准的 jQuery AJAX 配置项,jstree 还提供了data和url。 这两个选项的值可以是一个函数,函数将在实例范围内执行,并接收 1 个参数(正在加载的节点), 函数的返回值作为这两个配置项各自最终的值。
若服务器响应的头不是 JSON 类型,则应至少设值 jQuery AJAX 的选项dataType为json。
$('#tree').jstree({'core' : { 'data' : { 'url' : function (node) { return node.id === '#' ? 'ajax_roots.json' : 'ajax_children.json'; }, 'data' : function (node) { return { 'id' : node.id }; } }});
使用函数
还可提供一个函数。 此函数接收 2 个参数:
-
被加载的节点
-
一个回调函数,此回调函数接收包含子节点信息的参数
$('#tree').jstree({ 'core' : { 'data' : function (obj, cb) { cb.call(this, ['Root 1', 'Root 2']); } }});
