0

我知道我在某个地方弄乱了语法,但我不知道在哪里。代码如下。(我省略了body标签,因为它在预览中没有正确显示)

<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>
4

1 回答 1

1

假设您使用的是 .NET 3.5+ 并且 getProducts 返回一个像 List 或数组这样的集合,您需要考虑.NET 用 .NET 包装您的数据的 .d。由于您的{{each}}循环无论如何都需要对数组的引用,因此您可以通过更改模板来利用 .d ,如下所示:

<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>
于 2010-11-16T18:19:56.207 回答