A quick introduction of using jTemplate against AJAX JSON data
jQuery has a few template plugins, the most widely accepted is jTemplate. jTemplate is a JQuery template engine that works with AJAX and JSON data. We can use jTemplate in the following steps:
First, download the JQuery JavaScript file and reference it in your web page:
- <scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>
<scrip src="scripts/jQuery-jtemplates.min.js" type="text/javascript"></script>
Second, define your template:
- <script type="text/html" id="TemplateResultsTable">
- {#template MAIN}
- <table cellpadding="10" cellspacing="0">
- <tr>
- <th>Artist</th>
- <th>Company</th>
- <th>Title</th>
- <th>Price</th>
- </tr>
- {#foreach $T.d as CD}
- {#include ROW root=$T.CD}
- {#/for}
- </table>
- {#/template MAIN}
- {#template ROW}
- <tr class="{#cycle values=['','evenRow']}">
- <td>{$T.Artist}</td>
- <td>{$T.Company}</td>
- <td>{$T.Title}</td>
- <td>{$T.Price}</td>
- </tr>
- {#/template ROW}
- </script>
Please note that we define the template in a script block, which can be accessed by its id; also, $T is a reference to the data item passed to the template.
Third, call your web service in your script, designate the template and instantiate it with data.
- $(document).ready(function() {
- $.ajax({
- type: "POST",
- url: "CDCatalog.asmx/GetCDCatalog",
- data: "{}",
- contentType: "application/json; charset=utf-8",
- dataType: "json",
- success: function(msg) {
- //instantiate a template with data
- ApplyTemplate(msg);
- }
- });
- });
- function ApplyTemplate(msg) {
- $(‘#Container’).setTemplate($("#TemplateResultsTable").html());
- $(‘#Container’).processTemplate(msg);
- }
For more info please visit Xun Ding’s excellent article Using jQuery with ASP .NET
No comments yet.
