这是我的JSON,我想知道如何使用车把模板引擎将信息显示到页面中:
这是我的模板(脚本):
<script id="template-app" type="text/x-handlebars-template">
{{#each data}}
Email: {{email}} <br/>
First Name: {{first_name}} <br/>
Last Name: {{last_name}} <br/>
{{/each}}
</script>
然后我发送ajax请求以获取以下JSON:
$(function(){
var theTemplateScript= $("#template-app").html();
var theTemplate= Handlebars.compile(theTemplateScript);
$.ajax({
url: 'http://localhost/cb/MOCK_DATA.json',
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
var theCompiledHTML= theTemplate(data);
$(document.body).append(theCompiledHTML);
}
});
});
这是Ajax请求上方获得的JSON:
[{"first_name":"Betty","last_name":"Sims","email":"[email protected]"},
{"first_name":"Roger","last_name":"Mendoza","email":"[email protected]"},
{"first_name":"Albert","last_name":"West","email":"[email protected]"},
{"first_name":"Bobby","last_name":"Lane","email":"[email protected]"},
{"first_name":"Julie","last_name":"Wheeler","email":"[email protected]"}]
它不起作用,我相信它是从我编写的模板中获得的!
这是因为您说的是对每个data
,遍历数组。但是,您将普通的旧数组传递给Handlebar模板。它期望一个具有属性data
和数组值的对象。因此,您可以将Handlebars模板更改为:-
<script id="template-app" type="text/x-handlebars-template">
{{#each this}}
Email: {{email}} <br/>
First Name: {{first_name}} <br/>
Last Name: {{last_name}} <br/>
{{/each}}
</script>
--
或者,您可以修改JSON数据以使其与现有的Handlebars模板一起使用,如下所示:-
var json = {
data: [{
"first_name": "Betty",
"last_name": "Sims",
"email": "[email protected]"
}, {
"first_name": "Roger",
"last_name": "Mendoza",
"email": "[email protected]"
}, {
"first_name": "Albert",
"last_name": "West",
"email": "[email protected]"
}, {
"first_name": "Bobby",
"last_name": "Lane",
"email": "[email protected]"
}, {
"first_name": "Julie",
"last_name": "Wheeler",
"email": "[email protected]"
}]
};
对于您的JavaScript代码,您只需进行一些更改即可获得上述JSON:
$(function(){
var theTemplateScript= $("#template-app").html();
var theTemplate= Handlebars.compile(theTemplateScript);
$.ajax({
url: 'http://localhost/cb/MOCK_DATA.json',
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(result) {
var json_handlbars={
data:result
};
var theCompiledHTML= theTemplate(json_handlbars);
alert(theCompiledHTML);
$(document.body).append(theCompiledHTML);
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句