zoukankan      html  css  js  c++  java
  • JQuery实现分页程序代码

    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参数名称,获取参数的值

    复制代码
    <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代码如下,页面数据使用JQuery jTemplates绑定数据,非常方便,只需设置JSON格式数据,引用JS文件即可

     View Code

    <textarea id="tplList" style="display: none">
    <table class="cooltable" width="300px">
    <thead>
    <tr>
    <th align="center" scope="col" style="30px;"><input onclick="checkAllLine()" id="checkedAll" name="checkedAll" type="checkbox" title="全部选择/全部不选" /></th>
    <th scope="col" style="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="500px;">
    </div><br />
    <div id="ajaxPageBar" style="500px;">
    </div>

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


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

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

    Member_Ajax.aspx cs页面代码

     View Code

    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">参数名</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>
    /// 将字符串中的一些标签过滤
    /// </summary>
    /// <param name="theString"></param>
    /// <returns></returns>
    private static string SafetyQueryS(string theString)
    {
    string[] aryReg = { "'", ";", """, " ", " ", "<", ">" };
    for (int i = 0; i < aryReg.Length; i++)
    {
    theString = 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类型数据转换成JSON格式的数据,告别以前拼接成字串的方法

    Student实体类代码属性

     View Code

    public class Student
    {
    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
    }


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

     View Code

    public class PageBar
    {
    /// <summary>
    /// 完整模式:数字+上下页+首末+总记录信息+指定页码翻转
    /// </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() + "条,当前第" + currentPage.ToString() + "/" + pageCount.ToString() + "页&nbsp;&nbsp;&nbsp;</span>");
    sb.Append("<span class='total_count'>共" + countNum.ToString() + "条记录/" + pageCount.ToString() + "页&nbsp;&nbsp;</span>");
    if (countNum > pageSize)
    {
    if (currentPage != 1)//只要不是第一页
    sb.Append("<a target='_self' href='" + GetPageUrl(currentPage - 1, Http1, HttpM, HttpN, limitPage) + "' title='上一页'>&laquo;</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='下一页'>&raquo;</a>");
    if (stype == "html")
    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>");
    }
    sb.Append("</div>");
    return sb.ToString();
    }

    /// <summary>
    /// 分页导航
    /// </summary>
    /// <param name="mode">支持1=simple,2=normal,3=full</param>
    /// <param name="stype">html/js,只有当stype为html且mode为3的时候显示任意页的转向</param>
    /// <param name="stepNum">步数,如果步数为i,则每页的数字导航就有2i+1</param>
    /// <param name="countNum">记录总数</param>
    /// <param name="pageSize">每页记录数</param>
    /// <param name="currentPage">当前页码</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)//页数比较少
    {
    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());
    }
    }


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

     

     

     

     

     

     

  • 相关阅读:
    gym 101480 Problem C: Cow Confinement 题解
    Uva 1072 Huffman Codes 题解
    NERC 2015 Hypercube 题解
    ACM ICPC 2017 WF Problem J Son of Pipe Stream题解
    CF Round # 295 (Div. 1)题解
    CF 1444 D Rectangular Polyline 题解
    BZOJ3308 九月的咖啡店
    BZOJ4025 二分图
    BZOJ4000 [TJOI2015]棋盘
    BZOJ3999 [TJOI2015]旅游
  • 原文地址:https://www.cnblogs.com/Leo_wl/p/3223409.html
Copyright © 2011-2022 走看看