jquery - 如何在 Mustache 模板中循环遍历 Json 数组

标签 jquery mustache

我有一个包含 JSON 对象的数组:

{result" : "OK","data":[
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"},
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"}, 
                    {"name" : "henrytest",
                     "id" : "9a3d1faaaac742889a940a6d9df49d16"}
                   ]
 }

我正在尝试循环遍历数组以获取表中显示的 3 个字段。但是什么也没有显示。 这是我的 mustache 模板:

<table style="width:100%;">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>User ID</th>

                            </tr>
                        </thead>
                        <tbody>
                            {{#data}}
                                <tr>

                                    <td>{{name}}</td>
                                    <td>{{id}}</td>

                                </tr>
                              {{/data}}

                        </tbody>
</table>

我无法显示表中的任何字段。严重卡住了..:( :(有什么想法可以实现这一点吗?

最佳答案

刚刚浏览过mustache .我希望这正是您所期望的。

  $(document).ready(function() {
    var jsonData = {
      "result": "OK",
      "data": [{
        "name": "henrytest",
        "id": "9a3d1faaaac742889a940a6d9df49d16"
      }, {
        "name": "henrytest",
        "id": "9a3d1faaaac742889a940a6d9df49d16"
      }, {
        "name": "henrytest",
        "id": "9a3d1faaaac742889a940a6d9df49d16"
      }]
    }

    var Usertemplate = $("#user-template").html();
    $("#userinfo").html(Mustache.to_html(Usertemplate, jsonData));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.8.1/mustache.js"></script>
<table style="width:100%;">
  <thead>
    <tr>
      <th>Name</th>
      <th>User ID</th>
    </tr>
  </thead>
  <tbody id="userinfo">
    <script id="user-template" type="text-template">
      {{#data}}
      <tr>
        <td>{{name}}</td>
        <td>{{id}}</td>

      </tr>
      {{/data}}
    </script>
  </tbody>
</table>

关于jquery - 如何在 Mustache 模板中循环遍历 Json 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28791316/

相关文章:

javascript - Mustache.js 未正确呈现

java - Spring REST 文档抛出 MustacheException

jquery - 使用 jQuery 添加两个动态值

javascript - jQuery 按值选择单选?

javascript - 与 2 个 javascript 文件冲突

c++ - 如何使用 Boost.Xpressive 正确解析 Mustache?

java - mustache +吊带+CQ5

javascript - 如何在 mustache 模板化后检查元素是否存在

javascript - JQuery 根据不同元素中的文本获取标题值

jquery - 表单的 Django 小部件被忽略了吗? (datefield 和 modelchoice 上的 datepicker 和 tabindex)