地址:http://blueimp.github.io/JavaScript-Templates/
使用方式:
1、在客户端将模板文件引入
<script src="JS/tmpl.min.js"></script>
2、在客户端添加定义模板类型(o代表传入的json格式的数据)
<script type="text/x-tmpl" id="tmpl-demo"> <h3 style="color:red;">{%=o.Name%}</h3> <h4>年龄:{%=o.Age%}</h4> </script>
3、在客户端定义按钮(用来向服务端发送Ajax请求,获取JSON格式的数据)和数据显示区域
<div> <input type="button" value="点击" id="theBtn" /> </div> <div id="result"> </div>
4、按钮单击事件(用jquery处理)
<script type="text/javascript"> $(function () { $("#theBtn").click(function () { $.ajax({ type: "POST", url: "Handler/temp.ashx", contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { console.log(msg); $("#result").html(tmpl("tmpl-demo", msg)); }, error: function () { alert("An unexpected error has occurred during processing."); } }); }); }); </script>
5、在服务端添加Handler
public void ProcessRequest (HttpContext context) { context.Response.AddHeader("Vary", "Accept"); try { if (context.Request["HTTP_ACCEPT"].Contains("application/json")) context.Response.ContentType = "application/json"; else context.Response.ContentType = "text/plain"; } catch { context.Response.ContentType = "text/plain"; } JavaScriptSerializer js = new JavaScriptSerializer(); js.MaxJsonLength = 41943040; Customer theCustomer = new Customer(); theCustomer.Name = "息壤"; theCustomer.Age = 30; var jsonObj = js.Serialize(theCustomer); context.Response.Write(jsonObj); }
6、定义Customer类
public class Customer { public string Name { get; set; } public int Age { get; set; } public Customer(){} }