繁体   English   中英

在Handlebars.js中获取JSON内容

[英]Getting JSON content in Handlebars.js

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

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中的示例愿望清单项目:

"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();

})();

由于您已经在使用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
          }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM