如何从json文件(把手)

时间:2016-01-16 15:46:32

标签: javascript json handlebars.js

我有一个空的待办事项清单:

<ul class="list">

</ul>

我想在以下json数据中为每个json标题创建一个li列表:

[{"id":2,"title":"Mandar cartas a impresión","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:55.552Z","updated_at":"2015-12-07T13:09:55.552Z","project_id":1},{"id":3,"title":"CIF Intracomunitario","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:05.736Z","updated_at":"2015-12-07T13:10:05.736Z","project_id":1},{"id":4,"title":"Uniformes Chef a Porter","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:16.170Z","updated_at":"2015-12-07T13:10:16.170Z","project_id":1},{"id":5,"title":"Personal","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:10:31.569Z","updated_at":"2015-12-07T13:10:31.569Z","project_id":1},{"id":1,"title":"Mandar contrato pleni","description":"","status":false,"priority":1,"created_at":"2015-12-07T13:09:36.747Z","updated_at":"2015-12-07T13:13:12.068Z","project_id":1},{"id":17,"title":"Comprar TPV","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:40.753Z","updated_at":"2015-12-08T00:18:40.753Z","project_id":1},{"id":18,"title":"Vajillas Zara Home","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:18:54.580Z","updated_at":"2015-12-08T00:18:54.580Z","project_id":1},{"id":19,"title":"Tpv","description":"","status":false,"priority":null,"created_at":"2015-12-08T00:33:17.393Z","updated_at":"2015-12-08T00:33:17.393Z","project_id":1},{"id":21,"title":"Wifi - Contratar","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:24.639Z","updated_at":"2015-12-08T15:33:24.639Z","project_id":1},{"id":22,"title":"Cuenta Definitiva Santander","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:33:50.255Z","updated_at":"2015-12-08T15:33:50.255Z","project_id":1},{"id":23,"title":"Pagarés Kider","description":"","status":false,"priority":null,"created_at":"2015-12-08T15:34:08.162Z","updated_at":"2015-12-08T15:34:08.162Z","project_id":1}]

所以,我有以下javascript使用把手进行模板化:

 <script>    
    jQuery.getJSON("http://myurl/tasks.json", function(data){  
    var source   = $("#tasks-template").html();
    var template = Handlebars.compile(source);
      $.each(data) function() {
         var context = data;
         var show    = template(context);
        $(".list").html(show);
      });
    });         
    </script>

我的车把模板:

  <script id="tasks-template" type="text/x-handlebars-template">
    <li>
        <div>{{title}}</div>
    </li>
  </script>

它不会在我的html中为json中的每个标题创建一个li。

我错过了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

当您迭代JSON中收到的数组的每个对象时,您必须使用 this 而不是数据来访问该对象。 数据是整个数组,是您要检索title属性的当前对象:

$.each(data, function() {
     var context = this;
     var show    = template(context);
    $(".list").append(show);
  });

同时更改追加 html 方法,不要覆盖内容。

此致