我正在尝试让jsTree处理子节点的按需加载.我的代码是这样的:
jQuery('#introspection_tree').jstree({
"json_data" : {
"ajax" : {
url : "http://localhost/introspection/introspection/product"
}
},
"plugins" : [ "themes", "json_data", "ui" ]
});
从通话中返回的json是
[
{
"data": "Kit 1",
"attr": {
"id": "1"
},
"children": [
[
{
"data": "Hardware",
"attr": {
"id": "2"
},
"children": [
]
}
],
[
{
"data": "Software",
"attr": {
"id": "3"
},
"children": [
]
}
]
]
}
.....
]
每个元素都可能有很多孩子,树会很大.目前这是一次加载整个树,这可能需要一些时间.当用户打开子节点时,如何实现按需加载子节点,我该怎么办?
提前致谢.
Chr*_*ner 43
Irishka指出了我正确的方向,但并没有完全解决我的问题.我摆弄着她的回答,想出了这个.仅为了清楚起见,使用两个不同的服务器功能.第一个列出了顶级的所有产品,第二个列出了给定产品的所有子项:
jQuery("#introspection_tree").jstree({
"plugins" : ["themes", "json_data", "ui"],
"json_data" : {
"ajax" : {
"type": 'GET',
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1)
{
url = "http://localhost/introspection/introspection/product/";
}
else
{
nodeId = node.attr('id');
url = "http://localhost/introspection/introspection/children/" + nodeId;
}
return url;
},
"success": function (new_data) {
return new_data;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
从函数返回的json数据是这样的(注意每个节点中state = closed):
[
{
"data": "Kit 1",
"attr": {
"id": "1"
},
"state": "closed"
},
{
"data": "KPCM 049",
"attr": {
"id": "4"
},
"state": "closed"
},
{
"data": "Linux BSP",
"attr": {
"id": "8"
},
"state": "closed"
}
]
不需要静态数据,现在树在每个级别上都是完全动态的.
Rad*_*dek 12
我想默认显示第一级节点然后根据需要加载子节点会很好.在这种情况下,您唯一需要修改的是添加"state" : "closed"到其子节点将按需加载的节点.
您可能希望在ajax调用中发送节点的id,以便修改代码
"json_data": {
//root elements to be displayed by default on the first load
"data": [
{
"data": 'Kit 1',
"attr": {
"id": 'kit1'
},
"state": "closed"
},
{
"data": 'Another node of level 1',
"attr": {
"id": 'kit1'
},
"state": "closed"
}
],
"ajax": {
url: "http://localhost/introspection/introspection/product",
data: function (n) {
return {
"nodeid": $.trim(n.attr('id'))
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
来自jsTree文档
注意:如果同时设置了data和ajax,则从数据字符串呈现初始树.打开一个关闭的节点(没有加载的子节点)时,会发出一个AJAX请求.
Iri*_*hka 10
您需要在页面加载时将根元素设置为树数据,然后您将能够使用ajax请求检索其子项
$("#introspection_tree").jstree({
"plugins": ["themes", "json_data", "ui"],
"json_data": {
//root elements
"data": [{"data": 'Kit 1', "attr": {"id": 'kit1'}} /*, ... */], //the 'id' can not start with a number
"ajax": {
"type": 'POST',
"data": {"action": 'getChildren'},
"url": function (node) {
var nodeId = node.attr('id'); //id="kit1"
return 'yuorPathTo/GetChildrenScript/' + nodeId;
},
"success": function (new_data) {
//where new_data = node children
//e.g.: [{'data':'Hardware','attr':{'id':'child2'}}, {'data':'Software','attr':{'id':'child3'}}]
return new_data;
}
}
}
});
Run Code Online (Sandbox Code Playgroud)