In this example for each company in the list is shown one manager and nested list of all employees. Details about implementation is described in the sections below.
In the HTML should be placed one item that represents a template item that will be populated with elements from the JSON array. Example is shown below:
<ul><h2>Companies</h2> <li><a href="details.html" class="ID"> <span id="Name" class="Name"></span></a> <span id="Address" class="Address"></span> <h3>Manager:</h3> <span class="Manager"> <span class="FirstName"></span> <span class="LastName"></span> </span> <h3>Employees:</h3> <dl class="Employees"> <dt class="FirstName"></dt><dd class="LastName"></dd> </dl> </li> </ul>
In this template are placed three elements where properties ID, Name, and Address
of some JSON object will be populated. loadJSON plugin will take JSON array, bind
properties of the elements of the array to template and replicate template item
bound with each element in the array. Additionally, inside the LI element is placed
SPAN with class Manager where are placed two SPAN elements for manager's first name and last name,
and data list with class "Employees" where can be placed first and last name of employees.
Once HTML template item is prepared it is required to provide a JSON array that
will be used to populate template item shown above. Example of JSON array used in
this example is shown below:
[ { "ID": 17, "Name": "Emkay Entertainments", "Address": "Nobel House, Regent Centre", "Manager": { "FirstName": "John", "LastName": "Doe" }, "Employees": [ { "FirstName": "Brian", "LastName": "Hunt" }, { "FirstName": "Mick", "LastName": "Henning" } ] }, { "ID": 18, "Name": "The Empire", "Address": "Milton Keynes Leisure Plaza", "Manager": { "FirstName": "Ana", "LastName": "Johnsnon" }, "Employees": [ { "FirstName": "Erick", "LastName": "O'Neil" }, { "FirstName": "George", "LastName": "Halloway" } ] } ]
This array contains elements with properties ID, Name, and Address that will be
bound directly to the elements in the HTML template. Additionaly it has nested object
Manager with the FirstName and LastName properties, and nested array of Employees with
their own FirstName and LastName properties. JQuery loadJSON plugin generate nested list
Employees records inside each of the generated company records. This way is implemented
hierachical template for nested objects.
Template is defined in the LI HTML element, and under assumption that JSON
array is placed into the "hierarchy.js" file, the following code generates output HTML
using template and JSON array:
$('li').loadJSON('hierarchy.js');
As a results of this call will be generated output shown in the live example above.