使用存储在数组中的备用JSON格式创建动态jstree

我能够使用替代JSON格式创建jstree,如下所示:

$('#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,因为数据已经在数组中可用。

如果您希望数据是动态的,可以使用以下代码初始化您的jstree:

 $('#jstree').jstree({ 'core': { 'data': arrayCollection } }); 

其中arrayCollection是一个包含动态数组的变量。 例如,您的arrayCollection可能如下所示:

 var arrayCollection = [ {"id": "animal", "parent": "#", "text": "Animals"}, {"id": "device", "parent": "#", "text": "Devices"}, {"id": "dog", "parent": "animal", "text": "Dogs"}, {"id": "lion", "parent": "animal", "text": "Lions"}, {"id": "mobile", "parent": "device", "text": "Mobile Phones"}, {"id": "lappy", "parent": "device", "text": "Laptops"}, {"id": "daburman", "parent": "dog", "text": "Dabur Man", "icon": "/"}, {"id": "Dalmation", "parent": "dog", "text": "Dalmatian", "icon": "/"}, {"id": "african", "parent": "lion", "text": "African Lion", "icon": "/"}, {"id": "indian", "parent": "lion", "text": "Indian Lion", "icon": "/"}, {"id": "apple", "parent": "mobile", "text": "Apple IPhone 6", "icon": "/"}, {"id": "samsung", "parent": "mobile", "text": "Samsung Note II", "icon": "/"}, {"id": "lenevo", "parent": "lappy", "text": "Lenevo", "icon": "/"}, {"id": "hp", "parent": "lappy", "text": "HP", "icon": "/"} ]; 

最后,您的html文件应如下所示:

   JSTree       

每当修改arrayCollection时,都必须将arrayCollection重新分配给jstree并以编程方式刷新jstree。

 var fullMenuList = [ {"id": "1000", "parent": "#", "text": "PARENT"} ]; $http({ method: 'POST', url: 'Jtree.do', params: {} // pass in data as strings }).then(function (response) { console.log(response.data[0].Code1); console.log(response.data[0].Menu); console.log(response.data[0].Groupcode); for (var i = 0; i < response.data.length; i++) { fullMenuList.push({id: response.data[i].Code1, parent: response.data[i].Groupcode, text: response.data[i].Menu }); } $('#jstree').jstree({ "checkbox": { "keep_selected_style": false }, // "plugins": ["checkbox"], 'core': { 'data': fullMenuList } }); });