在Handlebars.js中获取JSON内容

时间:2014-10-16 19:57:28

标签: javascript json handlebars.js

我正在尝试在我的网站上创建一个愿望清单页面并且一切正常但我想通过从我的script.js文件中获取远程JSON文件而不是内联的内容来优化代码,我正在使用现在

JSON文件位于./js/content.json,需要通过script.js获取,以便它可以通过把手将其发送到HTML。

HTML(模板):

<script id="wishlist-item" type="text/template">
    <li><i class="{{icon}}"></i> <a href="{{url}}" target="_blank">{{title}} 
    <span class="valuta">&euro;{{price}}</span></a></li>
</script>

items.json中的wishlist项示例:

"items": [
        {
            "title": "A title",
            "icon": "fa fa-music",
            "location": "(Web)",
            "url": "http://linktowebsite.be",
            "price": 25.15
        },
        etc

的script.js:

(function(){
  function init(){

        var wishText = $('#wishlist-item').text(); //get the template from html
        var template = Handlebars.compile(wishText); //compile template to variable

        for(var i = 0; i <= wishlist.items.length-1; i++){ //loop data which is inline in var wishlist at the moment
            var wishlistItem = template(wishlist.items[i]); //set each item in the data as a template
            $('.wishlist').append(wishlistItem); //append to a div with class wishlist
        }
    }

  init();

})();

1 个答案:

答案 0 :(得分:4)

由于您已经在使用jQuery,请使用$.getJSON()

function init(){
    var wishText = $('#wishlist-item').text(); //get the template from html
    var template = Handlebars.compile(wishText); //compile template to variable

    $.getJSON("js/content.json", function(data) {
          for(var i = 0; i < data.items.length; i++){ //loop data which is inline in var wishlist at the moment
             var wishlistItem = template(data.items[i]); //set each item in the data as a template
              $('.wishlist').append(wishlistItem); //append to a div with class wishlist
          }
    });
}