【问题标题】:How to build a HTML from JSON and JQuery Templates如何从 JSON 和 JQuery 模板构建 HTML
【发布时间】:2011-05-10 23:24:28
【问题描述】:

我知道我在某个地方弄乱了语法,但我不知道在哪里。代码如下。 (我省略了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>

【问题讨论】:

  • 您收到的错误信息是什么?
  • 根据我的警报,我可以得到:“它可以工作”,但表格没有呈现。我看到的只是标题。我也没有收到错误消息。

标签: jquery html html-table jquery-templates


【解决方案1】:

假设您使用的是 .NET 3.5+ 并且 getProducts 返回一个像 List 或数组这样的集合,您需要考虑 the .d that .NET wraps your data with。由于您的 {{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>

【讨论】:

  • 啊。好的,我得到了正确数量的行,但是我得到了 Header 9 次(实际数据库表中有 9 条记录,所以那部分是正确的)。是的,我使用的是 .NET 4.0,并且 web 服务正在返回一个数组。
  • 我改变了主意,更新了我的答案。由于您的{{each}} 无论如何都需要引用来循环,只需传入data 而不是data.d,然后使用.d 指定您要循环的内容。这将解决您看到标题重复 9 次而不是 {{tmpl}} 被执行 9 次的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多