在上一篇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系列之目录汇总

转载于:https://blog.51cto.com/whitewolfblog/835204

JQuery模板插件jquery.tmpl-动态ajax扩展相关推荐

  1. Jquery 模板插件 jquery.tmpl.js 的使用方法(2):嵌套each循环,temp调用(使用预编译的模板缓存)...

    直接上代码吧 一:主窗口 /*#region SendChooseTargetTemplate 发送候选人主窗口模板*/ var SendChooseTargetTemplate = ''; Send ...

  2. jQuery分页插件(jquery.page.js)的使用

    效果描述: 不用分页即可显示的jQuery插件 jQuery分页插件--jQuery.page.js用法很简单,效果很棒 1.前端 首先html的head中引入相关css与js <link re ...

  3. SlidesJS基本使用方法和官方文档解释 【Jquery幻灯片插件 Jquery相册插件】

    SlidesJS基本使用方法和官方文档解释 [Jquery幻灯片插件 Jquery相册插件] 标签: jquery文档functionstringdiv相册 2012-04-19 15:23 3931 ...

  4. ajax 阻止默认提交,jQuery验证插件:在对ajax调用servlet时,submitHandler不会阻止默认提交-返回false无效...

    我有一个使用jquery和servlet的简单表单.jQuery对Servlet进行Ajax调用,然后Servlet进行一些服务器端计算,然后通过jQuery在同一页面上显示结果.我不希望表单进行默认 ...

  5. jQuery遮罩插件jQuery.blockUI.js简介

    概述: jQuery BlockUI插件可以在不锁定浏览器的同时,模拟同步模式下发起Ajax请求的行为.该插件激活时,会阻止用户在页面进行的操作,直到插件被关闭.BlockUI通过向DOM中添加元素实 ...

  6. jquery 滚轮插件 jquery.mousewheel.js

    jquery.mousewheel插件使用 jquery中没有鼠标滚轮事件,那么可以使用jquery的滚轮事件插件jquery.mousewheel.js. Github地址:jquery-mouse ...

  7. jquery模板插件jTemplates代替拼html

    jQuery的jTemplates插件允许定义一个显示模板,在展现数据时根据选择的模板来动态生成. jQuery的jTemplates官方网站:http://jtemplates.tpython.co ...

  8. 分享一款超棒的jQuery旋钮插件 - jQuery knob

    转自:http://www.cnblogs.com/gbin1/archive/2012/05/08/2489908.html 在线演示  本地下载 如果你也在寻找一款生成漂亮旋钮(knob)的jQu ...

  9. jQuery条形码插件 jQuery Barcode

    jQuery Barcode 是一个用来创建条形码的 jQuery 插件. 在线演示 首先介绍下条形码的原理先: 条形码技术最早产生在风声鹤唳的二十年代,诞生于Westinghouse的实验室里.一位 ...

最新文章

  1. 服务器崩溃日志 | 误删 OpenSSL 的那点事
  2. 三代测序数据分析之文献推荐
  3. 深入浅出OOP(四): 多态和继承(抽象类)
  4. python软件开发-Python -- 软件开发规范
  5. c++批量重命名_文件批量重命名?这个方法百试百灵
  6. 会计证考试《财经法规与职业道德》第一章精选题
  7. stay hungry stay foolish原文_弟子规原文+译文+注释
  8. mysql 在windows中安装问题
  9. [渝粤教育] 武汉交通职业学院 现代物流管理概论 参考 资料
  10. SQL Server 函数的使用(字符串函数)
  11. Java面试题-Java中的锁
  12. Python实现供应链数据分析
  13. java.util 语言_java中的import java.util是什么意思
  14. JAVA泛型尖括号中的 T 和 ? 有什么区别?
  15. 戴尔390计算机电源问题,DELL笔记本电脑电源适配器无电压输出故障
  16. [无私分享]最新网盘资源搜索站点
  17. Audition 入门系列(合集)_MediaTea的博客-CSDN博客
  18. 2020.09.29重读 原2020.08.04读 MoreFusion
  19. if 语句与switch语句
  20. Labview中运行时按钮不自动复位

热门文章

  1. 一维码EAN 8简介及其解码实现(zxing-cpp)
  2. Ubuntu 32下Android NDK+NEON的配置过程及简单使用举例
  3. html表格上下移动,Vue实现table上下移动功能示例
  4. linux挂载media装服务,CentOS8服务器入门系列教程(五):Linux挂载光盘、yum安装软件包...
  5. 136. 只出现一次的数字(关于异或的使用)
  6. linux rm 提示io异常,Hadoop异常 java.io.IOException: Job status not available
  7. c语言 字母 八进制表示'/1011',C语言C语言第一课:C语言概述为什么学习C语言怎样学习C语言.DOC...
  8. log4j在eclipse上使用简介
  9. php webapi验签,Asp.netCore3.0 WebApi从0到1手摸手教你写【5】增加接口参数签名验证...
  10. mysql 中文截取_mysql 截取中文字符