zoukankan      html  css  js  c++  java
  • Repeater 无刷新分页

    原文:http://blog.csdn.net/Sandy945/archive/2009/05/22/4208998.aspx

    本文讲述的是如何利用 XMLHttpRequest 来对 Repeater 控件 进行无刷新分页。

    实 现的方式是,使用XMLHttpRequest对象异步向服务器发送post 请求,传递设置好的每页显示记录数,当前页码和记录总数。服务器端接收到请求时,根据参数从数据库中查询相应记录,并通过Repeater 控件将数据显示出来,然后调用Repeater 的RenderControl 方法 将Repeater 绑定后生成的HTML代码作为服务器端的响应文本返回给客户端,客户端接到响应后替换Repeater 的相应HTML代码,从而实现了Repeater 无刷新分页。

    需要注意的地方:

    1、显示首页记录时,首页和上一页不可用,同理,显示末页记录时,末页和下一页不可用。

    2、重新设置每页显示记录数时,要保持当前的页码不变,分页数改变。

    下面看代码实现:

    首先,创建一个WEB窗体,命名为 RepeaterDemo.aspx

    代码如下:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterDemo.aspx.cs" Inherits="RepeaterDemo" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

    <html xmlns="http://www.w3.org/1999/xhtml " >
    <head runat="server">
        <title>无标题页</title>
        <style>
        <!--    
        .n{TEXT-DECORATION:none;cursor:pointer} a{color:black} a:hover{color:blue}
        .m{TEXT-DECORATION:none;cursor:default} a{color:black}
        //-->
        </style> 
        <script type="text/javascript">
            var xmlHttp=null;      
            var index,size="10";
            function $(id)
            {
                return document.getElementById(id);
            }
            function createXMLHttpRequest() 
            { 
                if(xmlHttp == null){
                    if(window.XMLHttpRequest) {
                        //Mozilla 浏览器
                        xmlHttp = new XMLHttpRequest();
                    }else if(window.ActiveXObject) {
                        // IE浏览器
                        try {
                            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
                        } catch (e) {
                            try {
                                xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                            } catch (e) {
                                alert('创建失败');
                            }
                        }
                    }
                }
            } 
            
            function openAjax(para) 
            {   
                if( xmlHttp == null)
                {                
                    createXMLHttpRequest();  
                    if( xmlHttp == null)
                    {
                        alert('出错');
                        return ;
                    }
                }                                                         
                
                xmlHttp.open("post","RepeaterDemoResult.aspx?date="+new Date().getTime(),true);             
                
                xmlHttp.onreadystatechange=xmlHttpChange;   
                
                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

                xmlHttp.send(para);           
            } 
            
            function xmlHttpChange() 
            {                     
                if(xmlHttp.readyState==4) 
                {             
                    if(xmlHttp.status==200) 
                    {                     
                        $('resultDiv').innerHTML=xmlHttp.responseText;                     
                        $('<%=lblCurrentPage.ClientID %>').innerText=index==null?$('<%=lblCurrentPage.ClientID %>').innerText:index;
                        if(index==1)
                        {
                            $('<%=lbtnFirst.ClientID %>').disabled=true;
                            $('<%=lbtnPrevious.ClientID %>').disabled=true;     
                            $('<%=lbtnFirst.ClientID %>').className='m';
                            $('<%=lbtnPrevious.ClientID %>').className='m';                                    
                        }
                        else
                        {
                            $('<%=lbtnFirst.ClientID %>').disabled='';
                            $('<%=lbtnPrevious.ClientID %>').disabled='';
                            $('<%=lbtnFirst.ClientID %>').className='n';
                            $('<%=lbtnPrevious.ClientID %>').className='n';      
                        }
                        if(index==document.getElementById('<%=lblPageCount.ClientID %>').innerText)
                        {
                            $('<%=lbtnNext.ClientID %>').disabled=true;
                            $('<%=lbtnLast.ClientID %>').disabled=true; 
                            $('<%=lbtnNext.ClientID %>').className='m';
                            $('<%=lbtnLast.ClientID %>').className='m';
                        }
                        else
                        {
                            $('<%=lbtnNext.ClientID %>').disabled=false;
                            $('<%=lbtnLast.ClientID %>').disabled=false;  
                            $('<%=lbtnNext.ClientID %>').className='n';
                            $('<%=lbtnLast.ClientID %>').className='n';       
                        }
                    } 
                } 
            } 
            function getHTML(operate)
            {
                if(event.srcElement.disabled)
                {
                    return;
                }
                var currentPage;
                var pageSize=$('<%=txtPageSize.ClientID %>').value;
                var count=$('<%=lblCount.ClientID %>').innerText;
                if(operate=='f')
                {
                    currentPage=1;                
                }
                else if(operate=='p')
                {
                    currentPage=parseInt($('<%=lblCurrentPage.ClientID %>').innerText)-1;              
                }
                else if(operate=='n')
                {
                    currentPage=parseInt($('<%=lblCurrentPage.ClientID %>').innerText)+1;
                }
                else if(operate=='l')
                {
                    currentPage=$('<%=lblPageCount.ClientID %>').innerText;
                }
                else if(operate=='c')
                {
                    currentPage=$('<%=lblCurrentPage.ClientID %>').innerText;
                    if(pageSize==size)
                    {
                        return ;
                    }
                    size=pageSize;           
                }
                else
                {
                    return ;
                }   
                index=currentPage;                    
                var para="pageNum="+currentPage+"&pageSize="+pageSize+"&count="+count;            
                openAjax(para);
            }
            function verify()
            {        
                if(isNaN(parseInt($('<%=txtPageSize.ClientID %>').value)))
                {
                    alert('请输入数字!');
                    return false;
                }            
                getHTML('c');
                var count=parseInt($('<%=lblCount.ClientID %>').innerText);
                if(isNaN(count))
                {
                    return;
                }
                var pageCount=(count%size==0)?count/size:(count-(count%size))/size+1;
                $('<%=lblPageCount.ClientID %>').innerText=pageCount;  
                var temp=parseInt($('<%=lblCurrentPage.ClientID %>').innerText);           
                if(pageCount<temp)
                {
                    $('<%=lblCurrentPage.ClientID %>').innerText=pageCount;
                    index=pageCount;
                }
            }
        </script>
    </head>
    <body>
        <form id="form1" runat="server">    
        <div id='resultDiv' style="cursor:auto">
            <asp:Repeater ID="rp" runat="server">
            <HeaderTemplate>
            <table><tr><td>编号</td><td>名称< /td><td>价格</td><td>库存</td></tr>
            </HeaderTemplate>
            <AlternatingItemTemplate><tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr></AlternatingItemTemplate>
            <ItemTemplate><tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr></ItemTemplate>
            <FooterTemplate>
            </table>
            </FooterTemplate>
            </asp:Repeater>        
        </div>
        每页显示<asp:TextBox ID="txtPageSize" runat="server" Text="10"></asp:TextBox>条记录&nbsp;&nbsp;&nbsp;& nbsp;<input type="button" value="设置" onclick="return verify();" /><br />  
        记录总数为:<asp:Label ID="lblCount" runat="server"></asp:Label>&nbsp;&nbsp;
        共分<asp:Label ID="lblPageCount" runat="server"></asp:Label>页&nbsp;&nbsp;
        当前为第<asp:Label ID="lblCurrentPage" runat="server"></asp:Label>页<br />    
        <asp:LinkButton ID="lbtnFirst" CssClass='n' OnClientClick="getHTML('f');return false;" Text="首页" runat="server"></asp:LinkButton>
        <asp:LinkButton ID="lbtnPrevious" CssClass='n' OnClientClick="getHTML('p');return false;" Text="上页" runat="server"></asp:LinkButton>
        <asp:LinkButton ID="lbtnNext" CssClass='n' OnClientClick="getHTML('n');return false;" Text="下页" runat="server"></asp:LinkButton>
        <asp:LinkButton ID="lbtnLast" CssClass='n' OnClientClick="getHTML('l');return false;" Text="末页" runat="server"></asp:LinkButton>
        </form>
    </body>
    </html>

    .cs 代码

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;


    using System.Data.SqlClient;
    using System.Text;

    public partial class RepeaterDemo : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                using (SqlConnection con=new SqlConnection("server=.;uid=sa;pwd=sa;database=Northwind"))
                {
                    SqlDataAdapter sda = new SqlDataAdapter("select count(*) from products", con);
                    DataSet ds = new DataSet();
                    sda.Fill(ds, "productsCount");
                    lblCount.Text = ds.Tables["productsCount"].Rows[0][0].ToString();
                    sda = new SqlDataAdapter("select * from products", con);
                    int count, pageCount, pageSize,currentPage;
                    int.TryParse(txtPageSize.Text, out pageSize);
                    pageSize = pageSize == 0 ? 10 : pageSize;
                    int.TryParse(lblCount.Text, out count);
                    pageCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
                    lblPageCount.Text = pageCount.ToString();
                    sda.Fill(ds, 0, pageSize, "products");
                    lblCurrentPage.Text = "1";
                    currentPage = 1;
                    rp.DataSource = ds.Tables["products"].DefaultView;
                    rp.DataBind();
                    //lbtnFirst.Enabled = false;
                    //lbtnPrevious.Enabled = false;
                    StringBuilder sb = new StringBuilder();
                    sb.Append("document.getElementById('" + lbtnFirst.ClientID + "').disabled=true;");
                    sb.Append("document.getElementById('" + lbtnPrevious.ClientID + "').disabled=true;");                          if (pageCount == currentPage)
                    {
                        //lbtnNext.Enabled = false;
                        //lbtnLast.Enabled = false;
                        sb.Append("document.getElementById('" + lbtnNext.ClientID + "').disabled=true;");
                        sb.Append("document.getElementById('" + lbtnLast.ClientID + "').disabled=true;"); 
                    }//end if block
                    ClientScript.RegisterStartupScript(GetType(), "disabled", "<script>" + sb.ToString() + "</script>");
                }//end using block
            }//end if block
        }//end Page_Load event
    }

    然后创建服务器端接收XMLHttpRequest 请求的文件,这里用的是WEB窗体,命名为 RepeaterDemoResult.aspx

    .aspx 代码如下:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterDemoResult.aspx.cs" Inherits="RepeaterDemoResult" %>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

    <html xmlns="http://www.w3.org/1999/xhtml " >
    <head runat="server">
        <title>无标题页</title>
    </head>
    <body>
        <form id="form1" runat="server">
        <asp:Repeater ID="rp" runat="server">
            <HeaderTemplate>
                <table><tr><td>编号</td><td>名称< /td><td>价格</td><td>库存</td></tr>
            </HeaderTemplate>
            <AlternatingItemTemplate>
                <tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr>
            </AlternatingItemTemplate>
            <ItemTemplate>
                <tr><td><%#Eval("ProductID") %></td><td><%#Eval("ProductName") %></td><td><%#Eval("UnitPrice") %></td><td><%#Eval("UnitsInStock") %></td></tr>
            </ItemTemplate>
            <FooterTemplate>
                </table>
            </FooterTemplate>
        </asp:Repeater>
        </form>
    </body>
    </html>

    .cs 代码如下:

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    using System.Data.SqlClient;
    using System.IO;

    public partial class ajax_xmlHttpRequest_RepeaterDemoResult : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection("server=.;uid=sa;pwd=sa;database=Northwind"))
            {
                SqlDataAdapter sda = new SqlDataAdapter("select * from products", con);
                DataSet ds = new DataSet();
                int count, pageSize, currentPage;
                int.TryParse(Request.Form["pageSize"], out pageSize);
                pageSize = pageSize == 0 ? 10 : pageSize;
                int.TryParse(Request.Form["count"], out count);
                int.TryParse(Request.Form["pageNum"], out currentPage);
                int tempCount = count % pageSize == 0 ? count / pageSize : count / pageSize + 1;
                if (tempCount < currentPage)
                {
                    currentPage = tempCount;
                }
                sda.Fill(ds, (currentPage - 1) * pageSize, pageSize, "products");
                rp.DataSource = ds.Tables["products"].DefaultView;
                rp.DataBind();
                Response.Clear();
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                rp.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
            }
        }
    }

    程序到这里已经完成了,可以运行看效果了。如果觉得样式简单,可以设置CSS来美观,这里主要是实现功能。

  • 相关阅读:
    [剑指Offer]判断一棵树为平衡二叉树(递归)
    [HDOJ]Coin Change(DP)
    01背包、完全背包
    [CodeForces_618C]Constellation
    [Codeforces_713A]Sonya and Queries
    C++位运算符
    [codeforces_597B] Restaurant(贪心)
    [LeetCode_98]Validate Binary Search Tree
    [LeetCode_96] Unique Binary Search Trees
    [LeetCode_105]Construct Binary Tree from Preorder and Inorder Traversal
  • 原文地址:https://www.cnblogs.com/lishuyi/p/4137566.html
Copyright © 2011-2022 走看看