在上一篇JQuery模板插件-jquery.tmpl中介绍了这款插件。有时我们需要去动态的ajax去加载模板,或者数据,根据url参数或者其他信息加载不同的模板,数据。在我的某个项目中有这个需求,所以特地写成jquery工具函数,加入了本地数据和ajax数据加载模板,数据的方式。

参数说明:

Tmpl: function(template, data, fun)

1:template:

1): url: 为ajax的加载url,ajax当且仅当remote= true时候加载。

2):data: 为ajax加载参数

3) templateSelector: 为本地模板选择器,当且仅当remote= false时使用

4) remote: true为ajax,false为本地数据,

5) cache: 指示是否对模板缓存。

2:data:

1): url: 为ajax的加载url,ajax当且仅当remote= true时候加载。

2):data: 为ajax加载参数

3) templateData: 为本地数据,当且仅当remote= false时使用

4) remote: true为ajax,false为本地数据,

5) cache: 指示是否对模板缓存。

3:fun为回调函数:

fun(jquery.tmpl对象,模板script,数据);

具体代码如下:

  1. View Code
  2. ; (function($) {
  3. $.extend({
  4. Tmpl_Data: function(te, data, fun, templatecache) {
  5. data = jQuery.extend({ data: "", url: "", templateData: {}, remote: true, cache: true }, data);
  6. if (!data.remote) {
  7. fun(te.tmpl(data.templateData), te, data.templateData);
  8. if (!templatecache) {
  9. te.remove();
  10. }
  11. return;
  12. }
  13. var da = te.data("objdata");
  14. if (data.cache && da != null && da != undefined) {
  15. fun(te.tmpl(da), te, da);
  16. if (!templatecache) {
  17. te.remove();
  18. }
  19. return;
  20. }
  21. $.ajax({
  22. type: "GET",
  23. data: data.data,
  24. url: data.url,
  25. dataType: "json",
  26. cache: false,
  27. context: { template: te, data: data },
  28. success: function(tmpldata) {
  29. fun(this.template.tmpl(tmpldata), this.template, tmpldata);
  30. if (data.cache) {
  31. this.template.data("objdata", tmpldata);
  32. }
  33. if (!templatecache) {
  34. this.template.remove();
  35. }
  36. },
  37. error: function(e) {
  38. throw "get data error(" + this.data.url + "?" + this.data.data + "):" + e;
  39. }
  40. });
  41. },
  42. JquerySelecotrCharChange: function(str) {
  43. return str.replace(".""\\.").replace("#""\\#");
  44. },
  45. Tmpl: function(template, data, fun) {
  46. template = jQuery.extend({ data: "", url: "", templateSelector: "", remote: true, cache: true }, template);
  47. if (!template.remote) {
  48. $.Tmpl_Data($(template.templateSelector), data, fun, true);
  49. return;
  50. }
  51. var te = null;
  52. try {
  53. te = $("script:[url='" + $.JquerySelecotrCharChange(template.url + "?" + template.data) + "']")
  54. }
  55. catch (e) {
  56. }
  57. if (template.cache && te != null && te.length > 0) {
  58. $.Tmpl_Data(te, data, fun, template.cache);
  59. return;
  60. }
  61. $.ajax({
  62. type: "GET",
  63. data: template.data,
  64. url: template.url,
  65. dataType: "html",
  66. cache: false,
  67. context: { template: template, data: data },
  68. error: function(e) {
  69. throw "get template error(" + this.template.url + "?" + this.template.data + "):" + e;
  70. },
  71. success: function(tmpltemplate) {
  72. var te = $('<script  type="text/x-jquery-tmpl">' + tmpltemplate + '<\/script>').appendTo(document.body);
  73. te.attr("url", (this.template.url + "?" + this.template.data));
  74. $.Tmpl_Data(te, this.data, fun, this.template.cache);
  75. }
  76. });
  77. }
  78. });
  79. })(jQuery);
  80. 复制代码

测试代码:

前台:

  1. View Code
  2. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Tmpl3.aspx.cs" Inherits="Tmpl3" %>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd%22>
  4. <html xmlns="http://www.w3.org/1999/xhtml%22>
  5. <head runat="server">
  6. <title></title>
  7. <script src="Script/jquery-1.6.4.js" type="text/javascript"></script>
  8. <script src="Script/jquery-jquery-tmpl-07d08cb/jquery.tmpl.js" type="text/javascript"></script>
  9. <script type="text/javascript" src="Script/Remote-Tmpl.js"></script>
  10. <script type="text/javascript">
  11. ; String.format = function() {
  12. var s = arguments[0];
  13. for (var i = 0; i < arguments.length - 1; i++) {
  14. var reg = new RegExp("\\{" + i + "\\}""gm");
  15. s = s.replace(reg, arguments[i + 1]);
  16. }
  17. return s;
  18. };
  19. function AjaxDeleteInvoke(id) {
  20. alert(String.format("AjaxDeleteInvoke:id={0}", id));
  21. }
  22. $(function() {
  23. $.Tmpl({ url: "TmplTemplate.htm", data: "test=1" }, { url: "Tmpl3.aspx", data: "ajax=1" }, function(t, te, da) {
  24. t.appendTo("#test>tbody");
  25. $("#test>tbody table").hide();
  26. $("#test .detailsImg").live("click"function() {
  27. var state = $(this).data("state");
  28. var $tr = $(this).parent().parent();
  29. if (state == "o") {
  30. $("table", $tr.next()).hide();
  31. $(this).data("state""c");
  32. $(this).attr("src""Image/folder_o.png");
  33. else {
  34. $("table", $tr.next()).show();
  35. $(this).data("state""o");
  36. $(this).attr("src""Image/folder_c.png");
  37. }
  38. });
  39. });
  40. //            $("#btntest").bind("click"function() {
  41. //            $.Tmpl({ url: "TmplTemplate.htm", data: "test=1" }, { url: "Tmpl3.aspx", data: "ajax=1" }, function(t, te, da) {
  42. //                    t.appendTo("#Table1>tbody");
  43. //                    $("#Table1>tbody table").hide();
  44. //                    $("#Table1 .detailsImg").live("click"function() {
  45. //                        var state = $(this).data("state");
  46. //                        var $tr = $(this).parent().parent();
  47. //                        if (state == "o") {
  48. //                            $("table", $tr.next()).hide();
  49. //                            $(this).data("state""c");
  50. //                            $(this).attr("src""Image/folder_o.png");
  51. //                        } else {
  52. //                            $("table", $tr.next()).show();
  53. //                            $(this).data("state""o");
  54. //                            $(this).attr("src""Image/folder_c.png");
  55. //                        }
  56. //                    });
  57. //                });
  58. //            });
  59. var data = new Array();
  60. for (var i = 0; i < 19; i++) {
  61. data.push(
  62. {
  63. Name: String.format("学生{0}", i),
  64. Sex: i % 2 == 0 ? "男" : "女",
  65. ID: i,
  66. Class:
  67. [
  68. {
  69. ClassName: String.format("Class{0}", i),
  70. Count: (i + 10) / 2
  71. },
  72. {
  73. ClassName: String.format("Class2{0}", i),
  74. Count: (i + 20) / 2
  75. }
  76. ]
  77. });
  78. }
  79. $("#btntest").bind("click"function() {
  80. $.Tmpl({ url: "TmplTemplate.htm", data: "test=1" }, { remote:false,templateData:data }, function(t, te, da) {
  81. t.appendTo("#Table1>tbody");
  82. $("#Table1>tbody table").hide();
  83. $("#Table1 .detailsImg").live("click"function() {
  84. var state = $(this).data("state");
  85. var $tr = $(this).parent().parent();
  86. if (state == "o") {
  87. $("table", $tr.next()).hide();
  88. $(this).data("state""c");
  89. $(this).attr("src""Image/folder_o.png");
  90. else {
  91. $("table", $tr.next()).show();
  92. $(this).data("state""o");
  93. $(this).attr("src""Image/folder_c.png");
  94. }
  95. });
  96. });
  97. });
  98. })
  99. </script>
  100. </head>
  101. <body>
  102. <form id="form1" runat="server">
  103. <div id="div1">
  104. <table style="margin-top: 10; margin-left: 300px;" border="1" cellpadding="0" cellspacing="0"
  105. id="test" width="500">
  106. <thead>
  107. <tr style="text-align: center; font-size: larger; font-weight: bolder;">
  108. <td>
  109. ID
  110. </td>
  111. <td>
  112. 姓名
  113. </td>
  114. <td>
  115. 性别
  116. </td>
  117. <td>
  118. 操作
  119. </td>
  120. </tr>
  121. </thead>
  122. <tbody>
  123. </tbody>
  124. </table>
  125. <hr />
  126. <p>
  127. 测试缓存系统(url)</p>
  128. <input type="button" id="btntest" value="testcache" />
  129. <table style="margin-top: 10; margin-left: 300px;" border="1" cellpadding="0" cellspacing="0"
  130. id="Table1" width="500">
  131. <thead>
  132. <tr style="text-align: center; font-size: larger; font-weight: bolder;">
  133. <td>
  134. ID
  135. </td>
  136. <td>
  137. 姓名
  138. </td>
  139. <td>
  140. 性别
  141. </td>
  142. <td>
  143. 操作
  144. </td>
  145. </tr>
  146. </thead>
  147. <tbody>
  148. </tbody>
  149. </table>
  150. </div>
  151. </form>
  152. </body>
  153. </html>
  154. 复制代码

后台ajax数据:

  1. View Code
  2. protected void Page_Load(object sender, EventArgs e)
  3. {
  4. if (Request["ajax"] == "1")
  5. {
  6. Response.Clear();
  7. Response.ContentType = "application/json";
  8. System.Text.StringBuilder sb = new System.Text.StringBuilder("[");
  9. for (int i = 0; i < 20; i++)
  10. {
  11. sb.AppendFormat(@" {{
  12. ""Name"":""学生{0}"",
  13. ""Sex"":""{1}"",
  14. ""ID"": {0},
  15. ""Class"":
  16. [
  17. {{
  18. ""ClassName"":""Class{0}"",
  19. ""Count"": {2}
  20. }},
  21. {{
  22. ""ClassName"":""Class2{0}"",
  23. "" Count"": {3}
  24. }}
  25. ]
  26. }},", i, i % 2 == 0 ? "" : "女", (i + 10) / 2, (i + 20) / 2);
  27. }
  28. sb.Remove(sb.Length - 1, 1);
  29. sb.Append("]");
  30. Response.Write(sb.ToString());
  31. Response.Flush();
  32. Response.Close();
  33. Response.End();
  34. }
  35. }
  36. 复制代码

效果如上一篇:

demo下载

其他资料:我jQuery系列之目录汇总