有如下数据列表,现在使用ArtTemplate模板引擎,搭配Ajax加载页面数据
Ajax页面响应如下JSON格式的数据源:
[
{"Id":1,"Name":"张三","Age":29},
{"Id":2,"Name":"李四","Age":27},
{"Id":3,"Name":"王五","Age":26},
{"Id":4,"Name":"赵六","Age":31},
{"Id":5,"Name":"钱七","Age":35}
]
插一个题外话,使用System.Web.Script.Serialization.JavaScriptSerializer().Serialize(list);即可对list集合进行JSON格式序列化
引用ArtTemplate模板引擎中的template-native.js文件,在页面中我们可以通过如下代码进行数据渲染:
<ul id="listUser"></ul>
<script id="templateUser" type="text/html">
<% for (var i=0;i<list.length;i++) { %>
<li>
编号:<%= list[i]["Id"] %><br />
姓名:<%= list[i]["Name"] %><br />
年龄:<%= list[i]["Age"] %>
</li>
<% } %>
</script>
<script type="text/javascript">
$.ajax({
url: "ajax.aspx",
type: "GET",
success: function(response) {
response = eval("(" + response + ")");
var json = { list: response };
var html = template("templateUser", json);
$("#listUser").html(html);
}
});
</script>
以<script id="templateUser" type="text/html">标签中的内容,使用for循环遍历list数组,返回填充过数据的html字符串,并将html字符串填充到#listUser元素中。
在静态的html页面中,我们这样使用没问题,但是放到动态的aspx页面中,模板引擎默认的“<%”和“%>”做为开启和闭合标记,在aspx页面中会被识别为服务端代码,页面无法通过编译。
这时,我们可以自定义模板引擎的开启和闭合标记:
<ul id="listUser"></ul>
<script id="templateUser" type="text/html">
${ for (var i=0;i<list.length;i++) { }$
<li>
编号:${= list[i]["Id"] }$<br />
姓名:${= list[i]["Name"] }$<br />
年龄:${= list[i]["Age"] }$
</li>
${ } }$
</script>
<script type="text/javascript">
$.ajax({
url: "ajax.aspx",
type: "GET",
success: function(response) {
response = eval("(" + response + ")");
var json = { list: response };
template.config("openTag", "${"); //此处自定义开启标记
template.config("closeTag", "}$");//此处自定义闭合标记
var html = template("templateUser", json);
$("#listUser").html(html);
}
});
</script>
OK,浏览页面,数据是否正确加载出来了呢?
以上代码,见此附件:
ArtTemplateDemo.zip