使用JQuery插件pagination实现AJax无刷新分页

以下只列出主要代码及注释,详细请参考最后源码:

我们需要用到的文件有:jquery.js,jquery.pagination.js,pagination.css

以及用于将DataTable转换为Json的插件Newtonsoft.Json.Net20.dll,文件在包含在最下面的源文件中

分页存储过程:

?
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      余泳彬
-- Create date: 2011-01-15 12:59
-- Description: 分页,用到了ROW_NUMBER()
-- =============================================
create PROCEDURE [dbo].[proc_FenYe]
@tblName   varchar (255),       -- 表名
@strFields varchar (1000) = '*' , -- 需要返回的列,默认*
@strOrder varchar (255)= '' ,      -- 排序的字段名,必填
@strOrderType varchar (10)= 'ASC' , -- 排序的方式,默认ASC
@PageSize   int = 10,          -- 页尺寸,默认10
@PageIndex int = 1,           -- 页码,默认1
@strWhere varchar (1500) = '' -- 查询条件 (注意: 不要加 where)
AS
 
declare @strSQL   varchar (5000)
 
if @strWhere != ''
set @strWhere= ' where ' +@strWhere
 
set @strSQL=
'SELECT * FROM (' +
     'SELECT ROW_NUMBER() OVER (ORDER BY ' +@strOrder+ ' ' +@strOrderType+ ') AS pos,' +@strFields+ ' ' +
     'FROM ' +@tblName+ ' ' +@strWhere+
') AS sp WHERE pos BETWEEN ' +str((@PageIndex-1)*@PageSize+1)+ ' AND ' +str(@PageIndex*@PageSize)
 
exec (@strSQL)

数据访问层主要函数:取出分页数据及计算总条数(主要看传的什么参数即可)

?
/// <summary>分页获取数据列表(所有字段+类名)</summary>
/// <param name="order">排序字段</param>
/// <param name="ordertype">排序类型:desc或asc</param>
/// <param name="PageSize">页大小</param>
/// <param name="PageIndex">页索引</param>
/// <param name="strWhere">条件</param>
/// <returns></returns>
public DataSet GetList( string order, string ordertype, int PageSize, int PageIndex, string strWhere)
{
     Database db = DatabaseFactory.CreateDatabase();
     DbCommand dbCommand = db.GetStoredProcCommand( "proc_FenYe" );
     db.AddInParameter(dbCommand, "tblName" , DbType.AnsiString, "News" );
     db.AddInParameter(dbCommand, "strFields" , DbType.AnsiString, "*" );
     db.AddInParameter(dbCommand, "PageSize" , DbType.Int32, PageSize);
     db.AddInParameter(dbCommand, "PageIndex" , DbType.Int32, PageIndex);
     db.AddInParameter(dbCommand, "strOrder" , DbType.String, order);
     db.AddInParameter(dbCommand, "strOrderType" , DbType.String, ordertype);
     db.AddInParameter(dbCommand, "strWhere" , DbType.AnsiString, strWhere);
     return db.ExecuteDataSet(dbCommand);
}
 
/// <summary>计算记录数</summary>
/// <param name="strWhere">条件</param>
/// <returns></returns>
public int CalcCount( string strWhere)
{
     string sql = "select count(1) from News" ;
     if (! string .IsNullOrEmpty(strWhere))
     {
         sql += " where " + strWhere;
     }
     Database db = DatabaseFactory.CreateDatabase();
     DbCommand dbCommand = db.GetSqlStringCommand(sql);
     return int .Parse(db.ExecuteScalar(dbCommand).ToString());
}

下面为主要代码:

1、页面引入JS及CSS

?
< script src = "js/jquery-1.4.2.js" type = "text/javascript" ></ script >
< script src = "js/jquery.pagination.js" type = "text/javascript" ></ script >
< link href = "Css/pagination.css" rel = "stylesheet" type = "text/css" />
< script src = "js/NewsAjaxPager.js" type = "text/javascript" ></ script >

2、页面Html代码

?
<!--内容列表--!>
< ul id = "PageContain" class = "newslist" >
     <!--加载图片--!>
     < li id = "loadImg" style = " width:100%; height:60px;text-align:center; margin-top:50px;" >< img src = "images/loading1.gif" ></ li >
     <!--内容会动态输出到这里面--!>
</ ul >
 
<!--页码,id不能改--!>
< div id = "Pagination" class = "digg" ></ div >

3、一般处理程序页面GetNewsList.ashx,根据条件取出分页数据及总条数

?
<%@ WebHandler Language= "C#" Class= "GetNewsList" %>
 
using System;
using System.Web;
using System.Data;
 
/// <summary>
/// 获取新闻列表,用于列表页AJAX分页及总条数
/// </summary>
public class GetNewsList : IHttpHandler
{
 
     DAl.NewsDAO newsDao = new DAl.NewsDAO();
     DAl.ProductCategoryDAO catDao = new DAl.ProductCategoryDAO();
 
     public void ProcessRequest(HttpContext context)
     {
         context.Response.ContentType = "text/plain" ;
 
         string action = context.Request[ "action" ];
 
         if (action == "pager" ) // 取出分页列表
         {
             // 排序字段
             string order = context.Request[ "order" ].ToString().Trim();
             string orderType = context.Request[ "orderType" ].ToString().Trim();
             // 页大小
             string pageSizeStr = context.Request[ "pageSize" ].ToString().Trim();
             int pageSize;
             int .TryParse(pageSizeStr, out pageSize);
             if (pageSize == 0)
             {
                 pageSize = 10;
             }
             // 页索引
             string pageIndexStr = context.Request[ "pageIndex" ].ToString().Trim();
             int pageIndex;
             int .TryParse(pageIndexStr, out pageIndex);
             if (pageIndex == 0)
             {
                 pageIndex = 1;
             }
 
             // 提取数据
             DataTable dt = newsDao.GetList(order, orderType, pageSize, pageIndex, StrWhere(context)).Tables[0];
             // 讲DataTable转换为Json
             string jsonDate = Common.WebHelper.DataTableToJSON(dt, "ListData" );
             context.Response.Write(jsonDate);
         }
         else if (action == "pageCount" // 获取总条数
         {
             context.Response.Write(newsDao.CalcCount(StrWhere(context)));
         }
 
     }
 
 
     /// <summary>
     ///  查询条件
     /// </summary>
     private string StrWhere(HttpContext context)
     {
         string strWhere = "IsShow='1'" ;
         string Id = context.Request[ "cid" ].ToString().Trim();
         if (! string .IsNullOrEmpty(Id)&&Common.WebHelper.IsPosInt(Id))
         {
             catDao.GetAllChildCatId(Id, ref Id);
             strWhere += "and CategoryID in (" + Id + ")" ; // ref Id
         }
         return strWhere;
     }
 
 
 
     public bool IsReusable
     {
         get
         {
             return false ;
         }
     }
 
}
DataTable转换为Json的函数
?
/*
  * 创建人:余泳彬
  * 创建时间:2011-1-17 9:59:50
  * 说明:网站帮助类(常用通用类)
  * 版权所有:余泳彬
  */
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using Newtonsoft.Json; // 需先添加引用
 
namespace Common
{
     /// <summary>网站帮助类</summary>
     public class WebHelper
     {
         /// <summary>将DateTable转为Json格式数据</summary>
         /// <param name="dt">要转换的DataTable名称</param>
         /// <param name="dtName">应该是转换后的Key如用Json.dtName得到数据</param>
         /// <returns></returns>
         public static string DataTableToJSON(DataTable dt, string dtName)
         {
             StringBuilder sb = new StringBuilder();
             StringWriter sw = new StringWriter(sb);
 
             using (JsonWriter jw = new JsonTextWriter(sw))
             {
                 JsonSerializer ser = new JsonSerializer();
                 jw.WriteStartObject();
                 jw.WritePropertyName(dtName);
                 jw.WriteStartArray();
                 foreach (DataRow dr in dt.Rows)
                 {
                     jw.WriteStartObject();
 
                     foreach (DataColumn dc in dt.Columns)
                     {
                         jw.WritePropertyName(dc.ColumnName);
                         ser.Serialize(jw, dr[dc].ToString());
                     }
 
                     jw.WriteEndObject();
                 }
                 jw.WriteEndArray();
                 jw.WriteEndObject();
 
                 sw.Close();
                 jw.Close();
 
             }
 
             return sb.ToString();
         }
 
     }
}
4、★主要的JS代码:(Ajax取出分页数据、总条数、绑定分页控件,讲分页数据HTML输出到前台)
?
/*
  * 余泳彬 2011-3-22
  * 利用Jquery的jquery.pagination.js插件进行Ajax分页
*/
 
 
$( function () {
     // 获取Url中的类别ID参数(logcheck.js)
     var CatId = GetQueryString( "cid" );
     // 计算分页总条数
     var pageCount = 0;
     $.ajax({
         type: "POST" ,
         cache: false ,
         async: false ,
         dataType: "text" ,
         url: "Handler/GetNewsList.ashx" ,
         data: "action=pageCount&cid=" + CatId,
         success: function (data) {
             pageCount = data;
             //alert(pageCount);
         }
     });
 
     // 初始化数据(显示第一页)
     InitData(CatId, "CreateDate" , "Desc" , 20, 0, pageCount);
 
     //处理翻页,page_id为当前页索引(0为第一页)
     function pageselectCallback(page_id, jq) {
         //alert(page_id);
         InitData(CatId, "CreateDate" , "Desc" , 20, page_id, pageCount);
     }
 
     // ★分页主函数(新闻类别ID,排序字段,排序类型,页大小,页索引,总条数)
     function InitData(CatId, order, ordertype, PageSize, pageindx, pageCount) {
         // Ajax取出分页列表数据
         $.ajax({
             type: "POST" ,
             cache: false ,
             dataType: "json" , // 数据格式:JSON
             url: "Handler/GetNewsList.ashx" ,
             data: "action=pager&cid=" + CatId + "&order=" + order + "&orderType=" + ordertype + "&pageSize=" + PageSize + "&pageIndex=" + (pageindx + 1),
             // 发送数据之前显示Loading图片,接收结束后隐藏
             beforeSend: function () { $( "#loadImg" ).show(); $( "#Pagination" ).hide() }, // 发送数据之前
             complete: function () { $( "#loadImg" ).hide(); $( "#Pagination" ).show() }, // 接收数据完毕
             // Ajax成功
             success: function (json) {
                 var listDate = json.ListData;
                 var html = "" ;
                 $.each(listDate, function (i, n) {
                     html += "<li class=\"b\"><span class=\"title\"><a href=\"newscontent.aspx?id=" + n.Id + "%>\" class=\"typelink\"  target=\"_blank\">" + n.LongTitle + "</a></span><span class=\"date\">" + n.CreateDate + "</span></li>" ;
                 });
                 // 输出HTML
                 $( "#PageContain" ).html(html);
             }
 
         }); // Ajax_end
 
 
         // 加入分页插件的绑定,第一个参数pageCount为总共多少条数据
         $( "#Pagination" ).pagination(pageCount, {
             callback: pageselectCallback,
             prev_text: '« 上一页' ,
             next_text: '下一页 »' ,
             items_per_page: PageSize,     // 每页显示条数
             current_page: pageindx,  // 当前页索引,这里0为第一页
             num_display_entries: 6,  // 前面显示几个按钮
             num_edge_entries: 2  // 后面显示几个按钮
         });
 
     // InitData_fun_end
 
 
});  // ready_end

实例完整源码:源码与上面所写稍有不同

jQueryPager(JQuery分页插件pagination实现Ajax分页).rar


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值