Madhura Indrazith
Madhura Indrazith

Reputation: 79

How to generate a tree based on input JSON using jQuery?

Firstly, I have to populate the data through a nested list.

Secondly have to write a CSS for adding images of expandable, collapsable and folder,lastly on clicking a generate link. It should display complete expanded tree.

      var dataSource = ({
           "Items": ({
            "Deserts": ({}),
            "Veg": ({
                "VegPulao": "Veg Pulao",
                "PalakPaneer": "Palak Paneer",
                "PaneerButterMasala": "Paneer Butter Masala"
            }),

            "Chicken": ({
                "Tandoori": "Tandoori special"
            }),
            "Hot drinks": ({
                "Coffe": ({ "Hot": "Hot Coffe", "Medium": "Medium", "Others": ({ "Iris": "Iris Coffe", "Capuccino": "Capuccino" }) }),
                "Tea": ({"Red": "Red Tea", "Black": "Black Tea"}),
                "BadamMilk": "Hot Badam Milk",
                "Bornvita": "Hot Bornvita",
                "Milk": "Hot Milk"
            }),
            "Juice": ({
                "Mango": "Mango",
                "Berry": "Berry",
                "Grapes": "Grapes",
                "Wine": ({
                    "Rose": "Rose",
                    "Red wine": "Red",
                    "Apple": "Apple",
                    "Hard drinks": ({
                        "Royal challenge": "Royal challenge",
                        "Blender's Pride": "Blender's Pride"
                    })
                })
            })

        })
    });

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<title>Tree Menu</title>
<meta charset="utf-8">
<link rel="stylesheet" href="css/style.css" type="text/css">
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/scripts.js"></script>
</head>
<body>
<a href="" id="mylink" style="font-family:Arial; color:blue;  margin:100px;">Generate Sorted List</a><br><br>
<div class="style"></div>
</body>
</html>

CSS code:

.style{
border:1px solid #A3A3C2;
width:425px;
height:500px;
float:left;
overflow: scroll;
}
 #expList .collapsed {
    list-style-image: url(../img/plusFolder.jpg);
}
#expList.expanded {
list-style-image: url(../img/minusFolder.jpg);
}
#expList.folder {
list-style-image: url(../img/Folder.jpg);
}

Upvotes: 2

Views: 1906

Answers (2)

AnilkumarTanneer
AnilkumarTanneer

Reputation: 21

Using AJAX

You can also use AJAX to populate the tree with JSON your server returns. The format remains the same as the above, the only difference is that the JSON is not inside the config object, but returned from the server.

To take advantage of this option you need to use the $.jstree.defaults.core.data config option.

Just use a standard jQuery-like AJAX config and jstree will automatically make an AJAX request populate the tree with the response.

In addition to the standard jQuery ajax options here you can supply functions for data and url, the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded, the return value of those functions will be used as URL and data respectively.

If you do not return correct json headers from the server, at least set the dataType jQuery AJAX option to "json".

By Uisng AJAX:

('#tree').jstree({
'core' : {
  'data' : {
    'url' : function (node) {
      return node.id === '#' ? 
        'ajax_roots.json' : 
        'ajax_children.json';
    },
    'data' : function (node) {
      return { 'id' : node.id };
    }
  }
});
/ 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
}

Using JSON: To Populate the tree with a JSON object you need to use the $.jstree.defaults.core.data config option.

$('#using_json').jstree({ 'core' : {
    'data' : [
       'Simple root node',
       {
         'text' : 'Root node 2',
         'state' : {
           'opened' : true,
           'selected' : true
         },
         'children' : [
           { 'text' : 'Child 1' },
           'Child 2'
         ]
      }
    ]
} });

Using functions:
You can supply a function too. That function will receive two arguments - the node being loaded and a callback function to call with the children for that node once you are ready.



$('#tree').jstree({
    'core' : {
        'data' : function (obj, cb) {
            cb.call(this,
              ['Root 1', 'Root 2']);
        }
    }});
		

Upvotes: 1

AnilkumarTanneer
AnilkumarTanneer

Reputation: 21

Using AJAX

You can also use AJAX to populate the tree with JSON your server returns. The format remains the same as the above, the only difference is that the JSON is not inside the config object, but returned from the server.

To take advantage of this option you need to use the $.jstree.defaults.core.data config option.

Just use a standard jQuery-like AJAX config and jstree will automatically make an AJAX request populate the tree with the response.

In addition to the standard jQuery ajax options here you can supply functions for data and url, the functions will be run in the current instance's scope and a param will be passed indicating which node is being loaded, the return value of those functions will be used as URL and data respectively.

If you do not return correct json headers from the server, at least set the dataType jQuery AJAX option to "json".

By Uisng AJAX:

('#tree').jstree({
'core' : {
  'data' : {
    'url' : function (node) {
      return node.id === '#' ? 
        'ajax_roots.json' : 
        'ajax_children.json';
    },
    'data' : function (node) {
      return { 'id' : node.id };
    }
  }
});
/ 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
}

Using JSON: To Populate the tree with a JSON object you need to use the $.jstree.defaults.core.data config option.

$('#using_json').jstree({ 'core' : {
    'data' : [
       'Simple root node',
       {
         'text' : 'Root node 2',
         'state' : {
           'opened' : true,
           'selected' : true
         },
         'children' : [
           { 'text' : 'Child 1' },
           'Child 2'
         ]
      }
    ]
} });

Upvotes: 1

Related Questions