How to initialize jsTree using JSON

I am doing jsTree this way:

$("#myTree").jstree({ "plugins": ["themes", "json_data", "ui", "crrm", "dnd"], "themes": { "theme": "default", "dots": false, "icons": false, "url": "../../Content/jsTreeThemes/default/style.css" }, "json_data": { "data" : [] } }); 

And the user sees the page with empty jsTree. I have to initialize jsTree when the user does some action. But I do not use ajax initialization (I do not use "ajax" in "json_data"). I have to initialize my jsTree using only the following line:

 var stringJSON = [{ "attr": { "id": "1", "rel": "root", "mdata": null }, "data": "title": "root_jsTree", "icon": null }, "state": "open", "children": [{ "attr": { "id": "7", "rel": "folder", "mdata": null }, "data": { "title": "1", "icon": null }, "state": "", "children": [{ "attr": { "id": "10", "rel": "folder", "mdata": null }, "data": { "title": "leaf", "icon": null }, "state": "", "children": [] }] }, { "attr": { "id": "8", "rel": "folder", "mdata": null }, "data": { "title": "leaf", "icon": null }, "state": "", "children": [{ "attr": { "id": "9", "rel": "folder", "mdata": null }, "data": { "title": "leaf", "icon": null }, "state": "", "children": [] }] }] }]' 

No matter how I get this line, when the user wants to see the tree, I already had this line. And here I ask the question: how can I initialize jsTree and display it for the user using only the line below.

+6
source share
2 answers

Maybe you want something like that? http://jsfiddle.net/radek/fmn6g/11/

  • Where I insert jsTree on button click.
  • The javascript on click function inserts a 'jstree' div, and also contains a jsTree definition.
  • As you can see, I also use the json data type.

Additional info in my question showing jsTree when clicked

This is what you need?

+5
source

Here is my solution:

 var jsTreeSettings = $("#myTree").jstree("get_settings"); jsTreeSettings.json_data.data = $.parseJSON(stringJSON); $.jstree._reference("myTree")._set_settings(jsTreeSettings); // Refresh whole our tree (-1 means root of tree) $.jstree._reference("myTree").refresh(-1); 

This solution will work even if we pre-installed AJAX to load the model.

From the documentation:

If both data and ajax are installed, the source tree is displayed from the data row. When you open a closed node (which has no children loaded), an AJAX request is made.

More information here http://www.jstree.com/documentation/json_data

I decided to use this solution because I have to change stringJSON several times and rebuild the tree using this changed string (without reloading the page).

+5
source

Source: https://habr.com/ru/post/900422/


All Articles