作为现代应用,ajax的大量使用,使得前端工程师们日常的开发少不了拼装模板,渲染模板

在刚有web的时候,前端与后端的交互,非常直白,浏览器端发出URL,后端返回一张拼好了的HTML串。浏览器对其进行渲染。html中可能会混有一些php(或者php中混有一些html)。在服务端将数据与模板进行拼装,生成要返回浏览器端的html串。

这与我们现在做一个普通网页没什么区别。只不过现在,我们更常使用模板技术来解决前后端耦合的问题。

前端使用模板引擎,在html中写一些标签,与数据与逻辑基本无关。后端在渲染的时候,解析这些标签,生成HTML串,如smarty。其实前端与后端的交互在服务端就已经有一次了。

下面是自己敲的案例,非常直观来渲染前端页面,可以复制来看看

可以参照GitHub上面来看https:///BorisMoore/jquery-tmpl

#container{
width: 400px;
min-height: 300px;
background-color: lightgreen;
margin: auto;
padding: 10px;
text-align: center;
}
li{
list-style: none;
text-align: left;
}
{{if weather}}
{{each weather as value}}

日期:{{value.date}}

  • 白天天气:{{value.info.day[1]}}
  • 白天温度:{{value.info.day[2]}}
  • 白天天气:{{value.info.day[3]}}
  • 白天天气:{{value.info.day[4]}}
  • 夜间天气:{{value.info.night[1]}}
  • 夜间温度:{{value.info.night[2]}}
  • 夜间天气:{{value.info.night[3]}}
  • 夜间天气:{{value.info.night[4]}}

{{/each}}
{{/if}}
$(function(){
$("#query").click(function(){
var code=$("#city").val();
$.ajax({
url : 'http://cdn.weather.hao.360.cn/api_weather_info.php',
data:{app:'hao360',code:code},
jsonp:'_jsonp',
jsonpCallback:'abc',
dataType:'jsonp',
success:function(data){
var html=template('weather',data);
$("#info").html(html);
}
})
})
})
 
 
北京
上海
广州
深圳