如何在胡子模板中循环遍历Json数组

时间:2015-03-01 07:49:40

标签: jquery mustache

我有一个带有JSON对象的数组:

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

我试图遍历数组以获取表格中显示的3个字段。然而,没有任何东西被曝光。 这是我的胡子模板:

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

我无法在表格中显示任何字段。严重对待.. :( :(任何想法我怎么能实现这个?

1 个答案:

答案 0 :(得分:4)

刚刚通过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>