[英]Getting JSON content in Handlebars.js
I'm trying to make a wishlist page on my website and everything works but I'd like to optimize the code by getting content from a remote JSON file instead of inline in my script.js file, which I'm using now. 我正在尝试在我的网站上创建一个愿望清单页面,并且一切正常,但是我想通过从远程JSON文件获取内容而不是在我现在使用的script.js文件中内联获取内容来优化代码。
The JSON file is located in ./js/content.json
and needs to be obtained by script.js so it can send it to the HTML with handlebars. JSON文件位于
./js/content.json
,需要通过script.js获取,以便可以将其发送到带有把手的HTML。
<script id="wishlist-item" type="text/template">
<li><i class="{{icon}}"></i> <a href="{{url}}" target="_blank">{{title}}
<span class="valuta">€{{price}}</span></a></li>
</script>
"items": [
{
"title": "A title",
"icon": "fa fa-music",
"location": "(Web)",
"url": "http://linktowebsite.be",
"price": 25.15
},
etc
(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();
})();
Since you're already using jQuery, use $.getJSON()
: 由于您已经在使用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.