In this example array of JavaScript objects is used as a data source for the list of elements. As you can see template for the first element is differnet than a template for the other ones. Details about implementation is described in the sections below.
JQuery loadJSON plugin enables you to load array of JavaScript objects into the list.
In the HTML should be placed one item for each element that should be generated and marked with rel="0", rel="1" etc so plugin can match array elements with HTML elements by indexes and rel attributes. Note that you migh skip indexes in the code and these array elements will be ignored.
<ul> <li rel="0"> <a href="details.html" class="ID"> <img class="Logo" alt="" src=""/> <span class="Name"></span> </a> <span class="Address"></span>, <span class="Town"></span> </li> <li rel="1"> <a href="details.html" class="ID"><span class="Name"></span></a> </li> <li rel="2"> <a href="details.html" class="ID"><span class="Name"></span></a> </li> <li rel="3"> <a href="details.html" class="ID"><span class="Name"></span></a> </li> </ul>
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", "Town": "Lothian", "Logo":"images/logo17.jpg" }, { "ID": 18, "Name": "The Empire", "Address": "Milton Keynes Leisure Plaza" }, { "ID": 19, "Name": "Asadul Ltd", "Address": "Hophouse" }, { "ID": 20, "Name": "Star Records", "Address": "St Danny Street" }, { "ID": 21, "Name": "Ashley Mark Publishing Company", "Address": "1-2 Vance Court" } ]
This array contains elements with properties ID, Name, and Address that will be bound to the elements in the HTML template.
When template and JSON are prepared they should be bound toghether in order to generate output. Template is defined in the UL HTML element, and under assumption that JSON array is placed into the "list.js" file, the following code generates output HTML using template and JSON array:
$('ul').loadJSON('list.js');