JQuery實現(xiàn)分頁程序代碼
做Web開發(fā)的程序員,分頁時在所難免的,微軟GridView、AspPager等設(shè)置分頁數(shù)據(jù)可以自動分頁,但是這里瀏覽器會閃動,用戶體驗不是很友好,在此我整理了JQuery實現(xiàn)分頁,并且使用。
JQuery綁定模板,顯示數(shù)據(jù)
首先Default.aspx頁面需要引用的JS文件
JQuery采用 1.4.1.1 下載地址:http://pan.baidu.com/share/link?shareid=3024434948&uk=2920032010
JQuery數(shù)據(jù)顯示模板JS 下載地址:http://pan.baidu.com/share/link?shareid=3030793948&uk=2920032010
分頁按鈕樣式 下載地址:http://pan.baidu.com/share/link?shareid=3146737028&uk=2920032010
Default.aspx頁面js代碼,如下,每頁條數(shù)可以自定義,也可以放置配置文件中,queryString函數(shù)是根據(jù)URL參數(shù)名稱,獲取參數(shù)的值
- <script type="text/javascript">
- var pagesize = 10;
- var page = thispage();
- $(document).ready(function () {
- ajaxList(page);
- });
- function queryString(pname) {
- var query = location.search.substring(1);
- var str = "";
- params = query.split("&");
- if (params.length > 0) {
- for (var n in params) {
- var pairs = params[n].split("=");
- if (pairs[0] == pname) {
- str = pairs[1];
- break;
- }
- }
- }
- return str;
- }
- function thispage() {
- var r = /^[1-9][0-9]*$/;
- if (queryString('page') == '') return 1;
- if (r.test(queryString('page')))
- return parseInt(queryString('page'));
- else
- return 1;
- }
- function ajaxList(currentpage) {
- if (currentpage != null) page = currentpage;
- $.ajax({
- type: "get",//get類型,獲取用QueryString方法,post類型,用Form獲取傳值
- dataType: "json",
- data: "pageIndex=" + currentpage + "&pagesize=" + pagesize + "&clienttt=" + Math.random(),
- url: "Member_Ajax.aspx",
- error: function (XmlHttpRequest, textStatus, errorThrown) { alert(XmlHttpRequest.responseText); },
- success: function (d) {
- switch (d.result) {
- case '-1':
- Alert(d.returnval);
- break;
- case '0':
- Alert(d.returnval);
- break;
- case '1':
- $("#ajaxList").setTemplateElement("tplList", null, { filter_data: true });
- $("#ajaxList").processTemplate(d);
- $("#ajaxPageBar").html(d.pagebar);
- break;
- }
- }
- });
- }
- </script>
Default.aspx頁面Form代碼如下,頁面數(shù)據(jù)使用JQuery jTemplates綁定數(shù)據(jù),非常方便,只需設(shè)置JSON格式數(shù)據(jù),引用JS文件即可
- <textarea id="tplList" style="display: none">
- <table class="cooltable" width="300px">
- <thead>
- <tr>
- <th align="center" scope="col" style="width:30px;"><input onclick="checkAllLine()" id="checkedAll" name="checkedAll" type="checkbox" title="全部選擇/全部不選" /></th>
- <th scope="col" style="width:60px;">ID</th>
- <th width="120px">姓名</th>
- <th scope="col" width="60px">年齡</th>
- </tr>
- </thead>
- <tbody>
- {#foreach $T.table as record}
- <tr>
- <td align="center">
- <input class="checkbox" name="selectID" type="checkbox" value='{$T.record.MemberNo}' />
- </td>
- <td align="center">{$T.record.Id}</td>
- <td align="left">
- {$T.record.Name}
- </td>
- <td align="left">
- {$T.record.Age}
- </td>
- </tr>
- {#/for}
- </tbody>
- </table>
- </textarea>
- <div id="ajaxList" style="width:500px;">
- </div><br />
- <div id="ajaxPageBar" style="width:500px;">
- </div>
$T.record.Id 中Id對應(yīng)的是實體類Id屬性
#p#
上面Javascript方法中用到Member_Ajax.aspx頁面代碼如下,注意:這里是將數(shù)據(jù)已JSON格式輸出到頁面,配合JQuery數(shù)據(jù)模板使用,所有Member_Ajax.aspx頁面,不應(yīng)該包含Html標(biāo)簽,其代碼格式如下
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Member_Ajax.aspx.cs" Inherits="Nick.Kuang.Web.Member_Ajax" %>
Member_Ajax.aspx cs頁面代碼
- protected void Page_Load(object sender, EventArgs e)
- {
- Response.Write(GetAll());
- }
- private string GetAll()
- {
- List<Student> list = new List<Student>();
- for (int i = 0; i < 100; i++)
- {
- list.Add(new Student { Id = i, Name = "Name" + i, Age = i });
- }
- int pageIndex = GetPage();
- int pageSize = StrToInt(QueryString("pagesize"), 10); ;
- JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
- string result = javascriptSerializer.Serialize(list.Skip(pageSize * (pageIndex - 1)).Take(pageSize).ToList());
- string response = "{\"result\" :\"1\"," +
- "\"returnval\" :\"操作成功\"," +
- "\"pagebar\" :\"" + PageBar.GetPageBar(3, "js", 2, list.Count, pageSize, pageIndex, "javascript:ajaxList(<#page#>);") + "\"," +
- "\"" + "totalCountStr" + "\":" + 10 + ",\"" + "table" + "\":" + result +
- "}";
- return response;
- }
- private static int GetPage()
- {
- int page = StrToInt(QueryString("pageIndex"), 0) < 1 ? 1 : StrToInt(QueryString("pageIndex"), 0);
- return page;
- }
- private static int StrToInt(string value, int defaultValue)
- {
- if (IsNumeric(value))
- return int.Parse(value);
- else
- return defaultValue;
- }
- /// <summary>
- /// 獲取querystring
- /// </summary>
- /// <param name="s">參數(shù)名</param>
- /// <returns>返回值</returns>
- private static string QueryString(string s)
- {
- if (HttpContext.Current.Request.QueryString[s] != null && HttpContext.Current.Request.QueryString[s] != "")
- {
- return SafetyQueryS(HttpContext.Current.Request.QueryString[s].ToString());
- }
- return string.Empty;
- }
- /// <summary>
- /// 將字符串中的一些標(biāo)簽過濾
- /// </summary>
- /// <param name="theString"></param>
- /// <returns></returns>
- private static string SafetyQueryS(string theString)
- {
- string[] aryReg = { "'", ";", "\"", "\r", "\n", "<", ">" };
- for (int i = 0; i < aryReg.Length; i++)
- {
- theStringtheString = theString.Replace(aryReg[i], string.Empty);
- }
- return theString;
- }
- private static bool IsNumeric(string value)
- {
- System.Text.RegularExpressions.Regex myRegex = new System.Text.RegularExpressions.Regex("^[-]?[1-9]*[0-9]*$");
- if (value.Length == 0)
- {
- return false;
- }
- return myRegex.IsMatch(value);
- }
使用JavaScriptSerializer中的Serialize方法可以將Object類型數(shù)據(jù)轉(zhuǎn)換成JSON格式的數(shù)據(jù),告別以前拼接成字串的方法
Student實體類代碼屬性
- public class Student
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public int Age { get; set; }
- }
#p#
分頁中用到的PageBar類代碼,分頁調(diào)用Default.aspx中ajaxList函數(shù),實現(xiàn)無刷新分頁
- public class PageBar
- {
- /// <summary>
- /// 完整模式:數(shù)字+上下頁+首末+總記錄信息+指定頁碼翻轉(zhuǎn)
- /// </summary>
- /// <param name="stype"></param>
- /// <param name="stepNum"></param>
- /// <param name="pageRoot"></param>
- /// <param name="pageFoot"></param>
- /// <param name="countNum"></param>
- /// <param name="currentPage"></param>
- /// <param name="Http1"></param>
- /// <param name="HttpM"></param>
- /// <param name="HttpN"></param>
- /// <param name="limitPage"></param>
- /// <returns></returns>
- 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)
- {
- StringBuilder sb = new StringBuilder();
- sb.Append("<div class='p_btns'>");
- //sb.Append("<span class='total_count'>共" + countNum.ToString() + "條,當(dāng)前第" + currentPage.ToString() + "/" + pageCount.ToString() + "頁 </span>");
- sb.Append("<span class='total_count'>共" + countNum.ToString() + "條記錄/" + pageCount.ToString() + "頁 </span>");
- if (countNum > pageSize)
- {
- if (currentPage != 1)//只要不是***頁
- sb.Append("<a target='_self' href='" + GetPageUrl(currentPage - 1, Http1, HttpM, HttpN, limitPage) + "' title='上一頁'>«</a>");
- if (pageRoot > 1)
- {
- sb.Append("<a target='_self' href='" + GetPageUrl(1, Http1, HttpM, HttpN, limitPage) + "'>1..</a>");
- }
- if (stepNum > 0)
- {
- for (int i = pageRoot; i <= pageFoot; i++)
- {
- if (i == currentPage)
- sb.Append("<span class='currentpage'>" + i.ToString() + "</span>");
- else
- sb.Append("<a target='_self' href='" + GetPageUrl(i, Http1, HttpM, HttpN, limitPage) + "'>" + i.ToString() + "</a>");
- if (i == pageCount)
- break;
- }
- }
- if (pageFoot < pageCount)
- {
- sb.Append("<a target='_self' href='" + GetPageUrl(pageCount, Http1, HttpM, HttpN, limitPage) + "'>.." + pageCount + "</a>");
- }
- if (currentPage != pageCount)//只要不是***一頁
- sb.Append("<a target='_self' href='" + GetPageUrl(currentPage + 1, Http1, HttpM, HttpN, limitPage) + "' title='下一頁'>»</a>");
- if (stype == "html")
- sb.Append("<span class='jumppage'>轉(zhuǎn)到第 <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>");
- }
- sb.Append("</div>");
- return sb.ToString();
- }
- /// <summary>
- /// 分頁導(dǎo)航
- /// </summary>
- /// <param name="mode">支持1=simple,2=normal,3=full</param>
- /// <param name="stype">html/js,只有當(dāng)stype為html且mode為3的時候顯示任意頁的轉(zhuǎn)向</param>
- /// <param name="stepNum">步數(shù),如果步數(shù)為i,則每頁的數(shù)字導(dǎo)航就有2i+1</param>
- /// <param name="countNum">記錄總數(shù)</param>
- /// <param name="pageSize">每頁記錄數(shù)</param>
- /// <param name="currentPage">當(dāng)前頁碼</param>
- /// <param name="Http1">第1頁的鏈接地址模板,支持js</param>
- /// <param name="HttpM">第M頁的鏈接地址模板,支持js,M不大于limitPage</param>
- /// <param name="HttpN">第N頁的鏈接地址模板,支持js,N大于limitPage</param>
- /// <param name="limitPage"></param>
- /// <returns></returns>
- public static string GetPageBar(int mode, string stype, int stepNum, int countNum, int pageSize, int currentPage, string Http1, string HttpM, string HttpN, int limitPage)
- {
- string pagebar = "";
- //if (countNum > pageSize)
- //{
- int pageCount = countNum % pageSize == 0 ? countNum / pageSize : countNum / pageSize + 1;
- currentPage = currentPage > pageCount ? pageCount : currentPage;
- currentPage = currentPage < 1 ? 1 : currentPage;
- int stepageSize = stepNum * 2;
- int pageRoot = 1;
- int pageFoot = pageCount;
- pageCount = pageCount == 0 ? 1 : pageCount;
- if (pageCount - stepageSize < 1)//頁數(shù)比較少
- {
- pageRoot = 1;
- pageFoot = pageCount;
- }
- else
- {
- pageRoot = currentPage - stepNum > 1 ? currentPage - stepNum : 1;
- pageFoot = pageRoot + stepageSize > pageCount ? pageCount : pageRoot + stepageSize;
- pageRoot = pageFoot - stepageSize < pageRoot ? pageFoot - stepageSize : pageRoot;
- }
- pagebar = GetDetailbar(stype, stepNum, pageRoot, pageFoot, pageCount, countNum, pageSize, currentPage, Http1, HttpM, HttpN, limitPage);
- return pagebar;
- }
- public static string GetPageBar(int mode, string stype, int stepNum, int countNum, int pageSize, int currentPage, string HttpN)
- {
- return GetPageBar(mode, stype, stepNum, countNum, pageSize, currentPage, HttpN, HttpN, HttpN, 0);
- }
- public static string GetPageUrl(int chkPage, string Http1, string HttpM, string HttpN, int limitPage)
- {
- string Http = string.Empty;
- if (chkPage == 1)
- Http = Http1;
- else
- Http = (chkPage > limitPage || limitPage == 0) ? HttpN : HttpM;
- return Http.Replace("<#page#>", chkPage.ToString());
- }
- }
代碼基本上寫好了,希望對大家有用,一起學(xué)習(xí),一起進(jìn)步。