jqueryhtmlhtml-tablejquery-templates

How to build a HTML from JSON and JQuery Templates


I know I'm messing up the syntax somewhere but I can't figure out where. Code below. (I left out the body tag because it wasn't showing correctly in the preview)

<head runat="server">
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tmpl.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tmplPlus.js" type="text/javascript"></script>
    <script id="ProductsTemplate" type="text/x-jquery-tmpl">
        <table class="productsHere">
            <thead>
                <tr>
                    <td>Title</td>
                    <td>Size</td>
                    <td>Price</td>
                </tr>
            </thead>
            <tbody>
                {{each data}}
                    {{tmpl($value) '#ProductsRowTemplate'}}
                {{/each}}
            </tbody>            
        </table>
    </script>
    <script id="ProductsRowTemplate" type="text/html">
        <tr>
            <td class="title">${title}</td>
            <td class="size">${size}</td>
            <td class="price">${price}</td>
        </tr>
    </script>
    <title>Using JQuery</title>
</head>

<script type="text/javascript">
    $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "JSON-WebService.asmx/getProducts",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $('#ProductsTemplate').tmpl(data).appendTo('#ProductsTable');
                alert("It works");
            },
            failure: function (data) {
                alert("It didn't work");
            }
        });
    });
</script>

<div id="ProductsTable"></div>
<div id="OthersTable"></div>
<div></div>

</form>

Solution

  • Assuming you're using .NET 3.5+ and getProducts returns a collection like a List or an array, you'll need to account for the .d that .NET wraps your data with. Since your {{each}} loop needs a reference to the array anyway, you can take advantage of the .d by changing your template like so:

    <script id="ProductsTemplate" type="text/x-jquery-tmpl">
      <table class="productsHere">
        <thead>
          <tr>
            <td>Title</td>
            <td>Size</td>
            <td>Price</td>
          </tr>
        </thead>
        <tbody>
          {{each d}}
            {{tmpl($value) '#ProductsRowTemplate'}}
          {{/each}}
        </tbody>
      </table>
    </script>