学习笔记之AJAX无刷新分页

时间:2022-02-23 08:11:07

利用AJAX实现无刷新分页技术原理:

其主要是利用AJAX的异步处理机制,实现数据的异步传递,它隐藏了客户端向服务端请求数据的状态,在客户端表现为无刷新的显示状态。

实现分页的步骤:

1.客服端点击页码按钮触发分页事件

2.客户端传递页码参数到服务端

3.服务端连接数据库获取数据

4.服务端将数据序列化并写入输出流

5.客户端获取输出流,并转换为JSON格式数据

6.将JSON数据组合排列到标签元素生成具体页面。

具体实例:

ASPX页面代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="jquery-1.4.1.js"></script>
     <script type="text/javascript">
         var pageCount = 0;
         var pageIndex = 1;
         $(function () {
             //getdata
             $.post("Pager.ashx", { "data": "getdata", "count": "1" }, function (data, status) {
                 var dd = $.parseJSON(data);
                 $(".con li").remove();
                 for (var i = 0; i < dd.length; i++) {
                     var li = $("<li>" + dd[i].datetime + ":" + dd[i].Msg + "</li>");                 
                     $(".con").append(li);
                 }
             });
             //getdatacount
             $.post("Pager.ashx", { "data": "getcount" }, function (data, status) {
                 //alert(data);
                 pageCount = data;
                 $(".b").text(data);
             });
             //尾页
             $(".pp li:eq(0) a").click(function (e) {
                 e.preventDefault();
                 $.post("Pager.ashx", { "data": "getdata", "pagecount": pageCount }, function (data, status) {
                     var dd = $.parseJSON(data);
                     $(".con li").remove();
                     for (var i = 0; i < dd.length; i++) {
                         var li = $("<li>" + dd[i].datetime + ":" + dd[i].Msg + "</li>");
                         $(".con").append(li);
                     }
                 });
             });
             //下页
             $(".pp li:eq(1) a").click(function (e) {
                 e.preventDefault();
                 if (pageIndex < pageCount) {
                     pageIndex++;

$.post("Pager.ashx", { "data": "getdata", "pagecount": pageIndex }, function (data, status) {
                         var dd = $.parseJSON(data);
                         $(".con li").remove();
                         for (var i = 0; i < dd.length; i++) {
                             var li = $("<li>" + dd[i].datetime + ":" + dd[i].Msg + "</li>");
                             $(".con").append(li);
                         }
                     });
                 }
             });
             //上一页
             $(".pp li:eq(2) a").click(function (e) {
                
                 e.preventDefault();
                 if (pageIndex > 1) {
                     pageIndex--;

$.post("Pager.ashx", { "data": "getdata", "pagecount": pageIndex }, function (data, status) {
                         var dd = $.parseJSON(data);
                         $(".con li").remove();
                         for (var i = 0; i < dd.length; i++) {
                             var li = $("<li>" + dd[i].datetime + ":" + dd[i].Msg + "</li>");
                             $(".con").append(li);
                         }
                     });
                 }
             });
             //首页
             $(".pp li:eq(3) a").click(function (e) {
                 e.preventDefault();
                 pageIndex = 1;

$.post("Pager.ashx", { "data": "getdata", "pagecount": pageIndex }, function (data, status) {
                     var dd = $.parseJSON(data);
                     $(".con li").remove();
                     for (var i = 0; i < dd.length; i++) {
                         var li = $("<li>" + dd[i].datetime + ":" + dd[i].Msg + "</li>");
                         $(".con").append(li);
                     }
                 });
             });
         })
     </script>
     <style type="text/css">
     li{ float:right; margin:0 2px 0; list-style:none;}
     .page{float:right; margin-right:1em;}
     .content{ clear:both;}
     .con li{ float:none; list-style:none; background-color:Gray;}
     a{ cursor:pointer;}
         .con
         {
             
             width: 400px;
         }
     </style>
</head>
<body>
    <form id="form1" runat="server">
    <div class="content" style=" width:600px; height:400px; border:1px solid red;">
    <ul class="con"></ul>
    </div>
    <div>
    <ul class="pp">
                  <li><a>尾页</a></li>
                  <li><a>下一页</a></li>
                  <li><a>上一页</a></li>
                  <li><a>首页</a></li>
    <li><div class="page">共有数据:<span class="b"></span></div></li>
    </ul>
    </div>
    </form>
</body>
</html>

后台处理程序ashx

<%@ WebHandler Language="C#" class="Pager" %>

using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public class Pager : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        string paras = context.Request.Params["data"].ToString();
        //string pagecount = ;
        if (paras == "getcount")
        {
            fenyeSlect ff = new fenyeSlect();
            DataTable dt = ff.selectCount().Tables[0];
            int count = Convert.ToInt32(dt.Rows[0][0].ToString());
            int pageCount = count / 10;
            if (count % 10 != 0)
            {
                pageCount++;
            }
            context.Response.Write(pageCount);
        }
        else if (paras == "getdata")
        {
            string pagenum = context.Request.Params["count"].ToString();

int ipagenum = Convert.ToInt32(pagenum);

fenyeSlect ff = new fenyeSlect();

DataSet ds = ff.GetPageData((ipagenum - 1) * 10 + 1, (ipagenum) * 10);

DataTable dt = ds.Tables[0];

List<News> list = new List<News>();

// string[] list00=new string[dt.Rows.Count];

for (int row = 0; row < dt.Rows.Count; row++)
            {
                //  list00[row] = dt.Rows[row][1].ToString();
                list.Add(new News { datetime = dt.Rows[row][1].ToString(), Msg = dt.Rows[row][2].ToString(), ID = dt.Rows[row][0].ToString() });
            }

JavaScriptSerializer jss = new JavaScriptSerializer();

string data = jss.Serialize(list);

context.Response.Write(data);
        }
      
        //context.Response.Write("Hello World");
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    public class fenyeSlect
    {
        public SqlConnection getconn()
        {
            string con = "server=.;uid=sa;pwd=nexel;database=wsxfy;";
            SqlConnection conn = new SqlConnection(con);
            return conn;
        }
        /// <summary>
        /// 获得条数,有多少条数据
        /// </summary>
        /// <returns></returns>
        public DataSet selectCount()
        {
            string selectCount = "SELECT COUNT(*) FROM T_Comment";
            DataSet ds = new DataSet();

SqlConnection conn = getconn();
            conn.Open();
            SqlDataAdapter da = new SqlDataAdapter(selectCount, conn);
            da.Fill(ds);
            return ds;

}
        public DataSet GetPageData(int StartRowIndex, int EndRowIndex)
        {
            //   string fenye = "select * from (select ID,Title,Person,[Time],Row_Number() over(order by ID desc) rownum from tb_IndustryNews)t where t.rownum>="+StartRowIndex+" and t.rownum<="+EndRowIndex+"";
            StringBuilder sql = new StringBuilder();
            sql.Append("select * from ( ");
            sql.Append("select ID,PostDate,Msg,Row_Number() over(order by ID desc) Rownum from T_Comment ");
            sql.Append(")t ");
            sql.Append("where t.Rownum>='" + StartRowIndex + "' and t.Rownum<='" + EndRowIndex + "'");

DataSet ds = new DataSet();

SqlConnection conn = getconn();
            conn.Close();
            SqlDataAdapter da = new SqlDataAdapter(sql.ToString(), conn);
            da.Fill(ds);
            return ds;
        }
    }
    public class News
    {
        public string datetime { get; set; }
        public string Msg { get; set; }
        public string ID { get; set; }
    }
}