这是我的代码
<script type="text/html" id='usageList'>
<table cellspacing='0' cellpadding='0' border='1' >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
/* I want to include data source via ajax or some mechanism here */
<%_.each(items,function(item,key,list){ %>
<% var f = item.name; %><!-- create more variables -->
<% var l= item.lastName; %>
<tr>
<!-- use variables -->
<td><%= key %></td>
<td class="<%= f %>"><%= f %></td>
<td class="<%= l %>"><%= l %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
答案 0 :(得分:1)
首先,将模板放入变量
var template = $('#usageList').html();
然后,发出Ajax请求。使用_.template
进程接收数据并将其添加到DOM节点
$.getJSON('ajax/test.json', function(data) {
$('#output').html(_.template(template,{items:data}));
});
返回的数据必须遵循此格式
[
{'name':'john', 'lastName':'M'},
{'name':'jean', 'lastName':'N'},
{'name':'carl', 'lastName':'K'},
{'name':'peter', 'lastName':'B'}
]
检查此JSFiddle:http://jsfiddle.net/jaimem/2gPYZ/