JQuery实现分页程序代码

开发 前端
做Web开发的程序员,分页时在所难免的,微软GridView、AspPager等设置分页数据可以自动分页,但是这里浏览器会闪动,用户体验不是很友好,在此我整理了JQuery实现分页,并且使用。

做Web开发的程序员,分页时在所难免的,微软GridView、AspPager等设置分页数据可以自动分页,但是这里浏览器会闪动,用户体验不是很友好,在此我整理了JQuery实现分页,并且使用。

JQuery绑定模板,显示数据

首先Default.aspx页面需要引用的JS文件

JQuery采用 1.4.1.1 下载地址:http://pan.baidu.com/share/link?shareid=3024434948&uk=2920032010

JQuery数据显示模板JS 下载地址:http://pan.baidu.com/share/link?shareid=3030793948&uk=2920032010

分页按钮样式 下载地址:http://pan.baidu.com/share/link?shareid=3146737028&uk=2920032010

Default.aspx页面js代码,如下,每页条数可以自定义,也可以放置配置文件中,queryString函数是根据URL参数名称,获取参数的值

  1. <script type="text/javascript">  
  2.         var pagesize = 10;  
  3.         var page = thispage();  
  4.         $(document).ready(function () {  
  5.             ajaxList(page);  
  6.         });  
  7.  
  8.         function queryString(pname) {  
  9.             var query = location.search.substring(1);  
  10.             var str = "";  
  11.             params = query.split("&");  
  12.             if (params.length > 0) {  
  13.                 for (var n in params) {  
  14.                     var pairs = params[n].split("=");  
  15.                     if (pairs[0] == pname) {  
  16.                         str = pairs[1];  
  17.                         break;  
  18.                     }  
  19.                 }  
  20.             }  
  21.             return str;  
  22.         }  
  23.  
  24.         function thispage() {  
  25.             var r = /^[1-9][0-9]*$/;  
  26.             if (queryString('page') == ''return 1;  
  27.             if (r.test(queryString('page')))  
  28.                 return parseInt(queryString('page'));  
  29.             else 
  30.                 return 1;  
  31.         }  
  32.  
  33.         function ajaxList(currentpage) {  
  34.             if (currentpage != null) page = currentpage;  
  35.             $.ajax({  
  36.                 type: "get",//get类型,获取用QueryString方法,post类型,用Form获取传值  
  37.                 dataType: "json",  
  38.                 data: "pageIndex=" + currentpage + "&pagesize=" + pagesize + "&clienttt=" + Math.random(),  
  39.                 url: "Member_Ajax.aspx",  
  40.                 error: function (XmlHttpRequest, textStatus, errorThrown) { alert(XmlHttpRequest.responseText); },  
  41.                 success: function (d) {  
  42.                     switch (d.result) {  
  43.                         case '-1':  
  44.                             Alert(d.returnval);  
  45.                             break;  
  46.                         case '0':  
  47.                             Alert(d.returnval);  
  48.                             break;  
  49.                         case '1':  
  50.                             $("#ajaxList").setTemplateElement("tplList"null, { filter_data: true });  
  51.                             $("#ajaxList").processTemplate(d);  
  52.                             $("#ajaxPageBar").html(d.pagebar);  
  53.                             break;  
  54.                     }  
  55.                 }  
  56.             });  
  57.         }  
  58.  
  59.  </script> 

Default.aspx页面Form代码如下,页面数据使用JQuery jTemplates绑定数据,非常方便,只需设置JSON格式数据,引用JS文件即可

  1. <textarea id="tplList" style="display: none"> 
  2.             <table class="cooltable" width="300px"> 
  3.             <thead> 
  4.                 <tr> 
  5.                     <th align="center" scope="col" style="width:30px;"><input onclick="checkAllLine()" id="checkedAll" name="checkedAll" type="checkbox" title="全部选择/全部不选" /></th> 
  6.                     <th scope="col" style="width:60px;">ID</th> 
  7.                     <th width="120px">姓名</th> 
  8.                     <th scope="col" width="60px">年龄</th> 
  9.                       
  10.                </tr> 
  11.             </thead> 
  12.             <tbody> 
  13.     {#foreach $T.table as record}  
  14.     <tr> 
  15.         <td align="center"> 
  16.             <input class="checkbox" name="selectID" type="checkbox" value='{$T.record.MemberNo}' /> 
  17.         </td> 
  18.         <td align="center">{$T.record.Id}</td> 
  19.         <td align="left"> 
  20.             {$T.record.Name}  
  21.         </td> 
  22.         <td align="left"> 
  23.             {$T.record.Age}  
  24.         </td> 
  25.     </tr> 
  26.     {#/for}  
  27. </tbody> 
  28.             </table> 
  29.      </textarea> 
  30.     <div id="ajaxList" style="width:500px;"> 
  31.     </div><br /> 
  32.     <div id="ajaxPageBar" style="width:500px;"> 
  33.     </div> 

$T.record.Id 中Id对应的是实体类Id属性

#p#

上面Javascript方法中用到Member_Ajax.aspx页面代码如下,注意:这里是将数据已JSON格式输出到页面,配合JQuery数据模板使用,所有Member_Ajax.aspx页面,不应该包含Html标签,其代码格式如下

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Member_Ajax.aspx.cs" Inherits="Nick.Kuang.Web.Member_Ajax" %> 

Member_Ajax.aspx cs页面代码

  1. protected void Page_Load(object sender, EventArgs e)  
  2.         {  
  3.             Response.Write(GetAll());  
  4.         }  
  5.  
  6.         private string GetAll()  
  7.         {  
  8.             List<Student> list = new List<Student>();  
  9.  
  10.             for (int i = 0; i < 100; i++)  
  11.             {  
  12.                 list.Add(new Student { Id = iName = "Name" + i, Age = i });  
  13.             }  
  14.               
  15.             int pageIndex = GetPage();  
  16.             int pageSize = StrToInt(QueryString("pagesize"), 10); ;  
  17.             JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();  
  18.  
  19.             string result = javascriptSerializer.Serialize(list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList());  
  20.             string response = "{\"result\" :\"1\"," +  
  21.                 "\"returnval\" :\"操作成功\"," +  
  22.                 "\"pagebar\" :\"" + PageBar.GetPageBar(3, "js", 2, list.Count, pageSize, pageIndex, "javascript:ajaxList(<#page#>);") + "\"," +  
  23.                "\"" + "totalCountStr" + "\":" + 10 + ",\"" + "table" + "\":" + result +   
  24.                 "}";  
  25.             return response;  
  26.         }  
  27.  
  28.         private static int GetPage()  
  29.         {  
  30.             int page = StrToInt(QueryString("pageIndex"), 0) < 1 ? 1 : StrToInt(QueryString("pageIndex"), 0);  
  31.             return page;  
  32.         }  
  33.  
  34.         private static int StrToInt(string value, int defaultValue)  
  35.         {  
  36.             if (IsNumeric(value))  
  37.                 return int.Parse(value);  
  38.             else  
  39.                 return defaultValue;  
  40.         }  
  41.  
  42.         /// <summary> 
  43.         /// 获取querystring  
  44.         /// </summary> 
  45.         /// <param name="s">参数名</param> 
  46.         /// <returns>返回值</returns> 
  47.         private static string QueryString(string s)  
  48.         {  
  49.             if (HttpContext.Current.Request.QueryString[s] != null && HttpContext.Current.Request.QueryString[s] != "")  
  50.             {  
  51.                 return SafetyQueryS(HttpContext.Current.Request.QueryString[s].ToString());  
  52.             }  
  53.             return string.Empty;  
  54.         }  
  55.  
  56.         /// <summary> 
  57.         /// 将字符串中的一些标签过滤  
  58.         /// </summary> 
  59.         /// <param name="theString"></param> 
  60.         /// <returns></returns> 
  61.         private static string SafetyQueryS(string theString)  
  62.         {  
  63.             string[] aryReg = { "'", ";", "\"", "\r", "\n", "<", ">" };  
  64.             for (int i = 0; i < aryReg.Length; i++)  
  65.             {  
  66.                 theStringtheString = theString.Replace(aryReg[i], string.Empty);  
  67.             }  
  68.             return theString;  
  69.         }  
  70.  
  71.         private static bool IsNumeric(string value)  
  72.         {  
  73.             System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex("^[-]?[1-9]*[0-9]*$");  
  74.             if (value.Length == 0)  
  75.             {  
  76.                 return false;  
  77.             }  
  78.             return myRegex.IsMatch(value);  
  79.         } 

使用JavaScriptSerializer中的Serialize方法可以将Object类型数据转换成JSON格式的数据,告别以前拼接成字串的方法

Student实体类代码属性

  1. public class Student  
  2.     {  
  3.         public int Id { get; set; }  
  4.  
  5.         public string Name { get; set; }  
  6.  
  7.         public int Age { get; set; }  
  8.     } 

#p#

分页中用到的PageBar类代码,分页调用Default.aspx中ajaxList函数,实现无刷新分页

  1. public class PageBar  
  2.     {  
  3.         /// <summary>  
  4.         /// 完整模式:数字+上下页+首末+总记录信息+指定页码翻转  
  5.      /// </summary>  
  6.         /// <param name="stype"></param>  
  7.         /// <param name="stepNum"></param>  
  8.         /// <param name="pageRoot"></param>  
  9.         /// <param name="pageFoot"></param>  
  10.         /// <param name="countNum"></param>  
  11.         /// <param name="currentPage"></param>  
  12.         /// <param name="Http1"></param>  
  13.         /// <param name="HttpM"></param>  
  14.         /// <param name="HttpN"></param>  
  15.         /// <param name="limitPage"></param>  
  16.         /// <returns></returns>  
  17.         private static string GetDetailbar(string stype, int stepNum, int pageRoot, int pageFoot, int pageCount, int countNum, int pageSize, int currentPage, string Http1, string HttpM, string HttpN, int limitPage)  
  18.         {  
  19.             StringBuilder sb = new StringBuilder();  
  20.             sb.Append("<div class='p_btns'>");  
  21.             //sb.Append("<span class='total_count'>共" + countNum.ToString() + "条,当前第" + currentPage.ToString() + "/" + pageCount.ToString() + "页&nbsp;&nbsp;&nbsp;</span>");  
  22.             sb.Append("<span class='total_count'>共" + countNum.ToString() + "条记录/" + pageCount.ToString() + "页&nbsp;&nbsp;</span>");  
  23.             if (countNum > pageSize)  
  24.             {  
  25.                 if (currentPage != 1)//只要不是***页  
  26.                     sb.Append("<a target='_self' href='" + GetPageUrl(currentPage - 1, Http1, HttpM, HttpN, limitPage) + "' title='上一页'>&laquo;</a>");  
  27.                 if (pageRoot > 1)  
  28.                 {  
  29.                     sb.Append("<a target='_self' href='" + GetPageUrl(1, Http1, HttpM, HttpN, limitPage) + "'>1..</a>");  
  30.                 }  
  31.                 if (stepNum > 0)  
  32.                 {  
  33.                     for (int i = pageRoot; i <= pageFoot; i++)  
  34.                     {  
  35.                         if (i == currentPage)  
  36.                             sb.Append("<span class='currentpage'>" + i.ToString() + "</span>");  
  37.                         else 
  38.                             sb.Append("<a target='_self' href='" + GetPageUrl(i, Http1, HttpM, HttpN, limitPage) + "'>" + i.ToString() + "</a>");  
  39.                         if (i == pageCount)  
  40.                             break;  
  41.                     }  
  42.                 }  
  43.                 if (pageFoot < pageCount)  
  44.                 {  
  45.                     sb.Append("<a target='_self' href='" + GetPageUrl(pageCount, Http1, HttpM, HttpN, limitPage) + "'>.." + pageCount + "</a>");  
  46.  
  47.                 }  
  48.                 if (currentPage != pageCount)//只要不是***一页  
  49.                     sb.Append("<a target='_self' href='" + GetPageUrl(currentPage + 1, Http1, HttpM, HttpN, limitPage) + "' title='下一页'>&raquo;</a>");  
  50.                 if (stype == "html")  
  51.                     sb.Append("<span class='jumppage'>转到第 <input type='text' name='custompage' size='2' onkeyup=\"this.value=this.value.replace(/\\D/g,'')\" onafterpaste=\"this.value=this.value.replace(/\\D/g,'')\" onkeydown=\"if(event.keyCode==13) {window.location='" + HttpN + "'.replace('<#page#>',this.value); return false;}\" /> 页</span>");  
  52.             }  
  53.             sb.Append("</div>");  
  54.             return sb.ToString();  
  55.         }  
  56.  
  57.         /// <summary>  
  58.         /// 分页导航  
  59.         /// </summary>  
  60.         /// <param name="mode">支持1=simple,2=normal,3=full</param>  
  61.         /// <param name="stype">html/js,只有当stype为html且mode为3的时候显示任意页的转向</param>  
  62.         /// <param name="stepNum">步数,如果步数为i,则每页的数字导航就有2i+1</param>  
  63.         /// <param name="countNum">记录总数</param>  
  64.         /// <param name="pageSize">每页记录数</param>  
  65.         /// <param name="currentPage">当前页码</param>  
  66.         /// <param name="Http1">第1页的链接地址模板,支持js</param>  
  67.         /// <param name="HttpM">第M页的链接地址模板,支持js,M不大于limitPage</param>  
  68.         /// <param name="HttpN">第N页的链接地址模板,支持js,N大于limitPage</param>  
  69.         /// <param name="limitPage"></param>  
  70.         /// <returns></returns>  
  71.         public static string GetPageBar(int mode, string stype, int stepNum, int countNum, int pageSize, int currentPage, string Http1, string HttpM, string HttpN, int limitPage)  
  72.         {  
  73.             string pagebar = "";  
  74.             //if (countNum > pageSize)  
  75.             //{  
  76.             int pageCount = countNum % pageSize == 0 ? countNum / pageSize : countNum / pageSize + 1;  
  77.             currentPage = currentPage > pageCount ? pageCount : currentPage;  
  78.             currentPage = currentPage < 1 ? 1 : currentPage;  
  79.             int stepageSize = stepNum * 2;  
  80.             int pageRoot = 1;  
  81.             int pageFoot = pageCount;  
  82.             pageCount = pageCount == 0 ? 1 : pageCount;  
  83.             if (pageCount - stepageSize < 1)//页数比较少  
  84.             {  
  85.                 pageRoot = 1;  
  86.                 pageFoot = pageCount;  
  87.             }  
  88.             else 
  89.             {  
  90.                 pageRoot = currentPage - stepNum > 1 ? currentPage - stepNum : 1;  
  91.                 pageFoot = pageRoot + stepageSize > pageCount ? pageCount : pageRoot + stepageSize;  
  92.                 pageRoot = pageFoot - stepageSize < pageRoot ? pageFoot - stepageSize : pageRoot;  
  93.             }  
  94.              
  95.             pagebar = GetDetailbar(stype, stepNum, pageRoot, pageFoot, pageCount, countNum, pageSize, currentPage, Http1, HttpM, HttpN, limitPage);  
  96.                    
  97.             return pagebar;  
  98.         }  
  99.  
  100.         public static string GetPageBar(int mode, string stype, int stepNum, int countNum, int pageSize, int currentPage, string HttpN)  
  101.         {  
  102.             return GetPageBar(mode, stype, stepNum, countNum, pageSize, currentPage, HttpN, HttpN, HttpN, 0);  
  103.         }  
  104.  
  105.         public static string GetPageUrl(int chkPage, string Http1, string HttpM, string HttpN, int limitPage)  
  106.         {  
  107.             string Http = string.Empty;  
  108.             if (chkPage == 1)  
  109.                 Http = Http1;  
  110.             else 
  111.                 Http = (chkPage > limitPage || limitPage == 0) ? HttpN : HttpM;  
  112.             return Http.Replace("<#page#>", chkPage.ToString());  
  113.         }  
  114.     } 

代码基本上写好了,希望对大家有用,一起学习,一起进步。

原文链接:http://www.cnblogs.com/nickkuang/p/3222416.html

责任编辑:林师授 来源: 博客园
相关推荐

2010-01-22 15:09:11

VB.NET下载程序

2010-07-17 00:55:48

PHP Telnet

2011-11-09 13:59:27

代码腐烂

2009-06-03 14:42:21

Eclipse调试调试Java程序

2010-07-13 09:29:37

socketUDP协议

2011-11-03 15:44:10

程序员

2009-06-17 14:29:50

java程序代码

2010-01-15 10:48:29

C++程序代码

2010-03-23 14:12:43

Python开发Win

2013-12-02 15:25:38

jQuery插件

2009-08-24 18:06:36

源程序代码C#读取XML文件

2010-01-15 18:46:08

C++程序代码

2009-09-02 18:28:00

C#鼠标位置

2014-01-16 13:36:17

2010-05-28 10:53:07

Linux串口测试工具

2013-04-22 11:34:30

BadNews恶意程序移动安全

2023-11-17 11:55:54

Pythonretrying库

2021-05-07 09:00:00

JavaScript开发代码

2009-10-27 10:14:54

VB.NET正则表达式

2011-08-08 10:42:46

iPhone UITableVie 分页
点赞
收藏

51CTO技术栈公众号