Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsTree with custom json data

I have this structure in json I can not be modified by request.

{
        "Object": [
            {
                "url": "http://www.google.com"
            }            
        ],
        "id": 1,
        "name": "Redirection Rule",
        "Object": {
            "frequency": 1,
            "trigger": 1
        },
        "Object": {
            "http": "Redirect Url",
            "response": 301
        }
    }

I need to use this structure to populate a jstree . I just need to use the "id" fields and "name", how do I set jstree to use "name" instead of "text" as a node name ?

like image 293
Crapo Wolf Avatar asked May 18 '15 18:05

Crapo Wolf


People also ask

What is jstree?

jsTree is jquery plugin, that provides interactive trees. It is absolutely free, open source and distributed under the MIT license. jsTree is easily extendable, themable and configurable, it supports HTML & JSON data sources and AJAX loading.

How do I use JSON with jstree?

jsTree needs a specific format to work with JSON. In the standard syntax no fields are required - pass only what you need. Keep in mind you will be able to access any additional properties you specify - jsTree won't touch them and you will be able to use them later on (using the original property on each node).

How to add additional information about selection changes in jstree?

This plugin adds additional information about selection changes. Once included in the plugins config option, each changed.jstree event data will contain a new property named changed, which will give information about selected and deselected nodes since the last changed.jstree event

How do I make an Ajax request from jstree?

Just use a standard jQuery-like AJAX config and jstree will automatically make an AJAX request populate the tree with the response. Add a class of jstree-closed to any LI node you return and do not nest an UL node and jstree will make another AJAX call as soon as the user opens this node.


1 Answers

Either:

1) use the jQuery dataFilter option (this means defining a function for dataFilter in your core.data jsTree config),

or

2) set core.data itself to a function, manually make the request and transform it like so:

$('#your-tree').jstree({
    core : {
        data : function (node, cb) {
            $.ajax({ url : ... }).done(function (data) {
                cb([{ "id" : data.id, "text" : data.name }])
            });
        }, ...

You can find more info on setting core.data to a function here: https://github.com/vakata/jstree#populating-the-tree-using-a-callback-function

like image 154
vakata Avatar answered Oct 09 '22 21:10

vakata