1)先引入artTemplate/template-native.js
2)准备一个script标签存放html,模板需要一个id,方便模板引擎,并且必须设置type类型
所谓模板引擎的作用就是帮我们将数据和html拼接好,将拼接好的结果返回给我们
<script id="rightCateTpl" type="text/html">
<a href="#" class="active">运动馆</a>
</script>
3.书写模板,进行ajax请求,需要用一个入口函数进行包装 第一个ajax获取到的是一级分类的数据,二级分类数据。
初始页面的设置
<script id="leftCateTpl" type="text/html">
<% for(var i=0;i<data.length;i++){ %>
<a href="javascript:;"data-id="<%=data[i].id %>" class="items getSecond"><%= data[i].categoryName %></a>
<%}%>
</script>
$.ajax({
type:'get',
url:'/category/queryTopCategory',
success:function(result){
$('#leftCate').html(template('leftCateTpl',{data:result.rows}))
if(result.rows.length > 0){
var id = result.rows[0].id;
$.ajax({
type:'get',
url:'/category/querySecondCategory',
data:{
id:id
},
success:function(result){
$('#rightCate').html(template('rightCateTpl',{data:result.rows}))
$('#leftCate').find('a:first-child').addClass('active');
}
})
}
}
});
4.右侧内容区版模板生成,发送ajax请求,获取到的是二级分类的数据
点击一级分类获取到二级分类的数据:1)一级分类添加点击事件 2)在事件处理函数中获取到一级分类的ID 3)调用二级分类的接口获取到对应的数据
4)将数据展示到对应的位置中 5)如果接口没有数据要在页面中显示暂无数据。
<script id="rightCateTpl" type="text/html">
<% for(var i=0;i<data.length;i++){ %>
<a href="javascript:;" class="items">
<img src="<%=data[i].brandLogo %>">
<span><%=data[i].brandName %></span>
</a>
<% } %>
<% if(!data.length){ %>
<span>暂无数据</span>
<% } %>
</script>
$('body').on('tap','.getSecond',function(){
var id = $(this).attr('data-id');
$(this).addClass('active').siblings().removeClass('active');
$.ajax({
type:'get',
url:'/category/querySecondCategory',
data:{
id:id
},
success:function(result){
$('#rightCate').html(template('rightCateTpl',{data:result.rows}))
}
})
});
模板引擎小知识点:1)<%=result[i].categoryName 输出result第i个元素中的某个方法 2)ajax请求获得的数据result是json数据,result.rows获得的是以索引方式呈现的二维数组,
将数据和html做拼接:1)html模板ID 2)数据 3)告诉模板引擎html模板和数据怎样进行拼接
使用模板引擎拼接方式:template('leftCateTpl',{data:result.rows})
在$(‘#leftCate’)html()中插入模板引擎拼接好的字符串, $('#leftCate').html(template('leftCateTpl',{data:result.rows}))