前段时间自己研究JQuery时,觉得JQuery很强大,在项目中就用到了AJAX的分页,实现思路是:
1.利用$.fn.extend在JQuery框架下扩展pager类
2.将获取记录总数与相应页记录的后台方法,写在继承自IHttpHandler类的Handler.ashx.cs类,当然实际上用aspx.cs文件写后台方法也没问题,但由于.ashx.cs文件无需处理页面诸多事件因而效率更高。
3.在呈现页面上加载pager类
以下是实现的代码:
1.扩展pager类:extend.js
Code
(function($){
$.fn.extend({
pager: function(totalCount,options) {
var opts = jQuery.extend({
pageSize:10,
callback:function(){}
}, options);
return this.each(function(){
var panel = $(this);
function pageCount(){
return Math.ceil(totalCount/opts.pageSize);
}
function selectPage(type){
return function(){
var page = parseInt($('#currentPage').val());
if(type=='first') $('#currentPage').val('1');
if(type=='last') $('#currentPage').val($('#totalCount').val());
if(type=='previous') {
if ((page-1)==0) $('#currentPage').val('1');
else $('#currentPage').val(page-1);
}
if(type=='next') {
if ((page+1)>parseInt($('#totalCount').val())) $('#currentPage').val($('#totalCount').val());
else $('#currentPage').val(page+1);
}
//go按钮
if(type=='go'){
if(isNaN($('input.page-index').val())||$('input.page-index').val()=='') return false;
var textIndex = parseInt($('input.page-index').val());
$('#currentPage').val(textIndex);
if(textIndex < 1) $('#currentPage').val('1');
else if(textIndex > parseInt($('#totalCount').val())) $('#currentPage').val($('#totalCount').val());
}
$("input.page-next").attr("disabled","");
$("input.page-last").attr("disabled","");
$("input.page-first").attr("disabled","");
$("input.page-previous").attr("disabled","");
if (parseInt($('#currentPage').val()) == 1){
$("input.page-first").attr("disabled","disabled");
$("input.page-previous").attr("disabled","disabled")
}
if (parseInt($('#currentPage').val()) == parseInt($('#totalCount').val())){
$("input.page-next").attr("disabled","disabled");
$("input.page-last").attr("disabled","disabled");
}
opts.callback(parseInt($('#currentPage').val()));
$('span.page-info').html($('#currentPage').val() + '/' + $('#totalCount').val());
}
}
function render(){
var html = '<table><tbody><tr>'
+'<td><span class="page-info">1' + '/'+ pageCount() + '</span></td>'
+'<td><input class="page-first" type="button" value=" << " /></td>'
+'<td><input class="page-previous" type="button" value=" < " /></td>'
+'<td><input class="page-next" type="button" value=" > " /></td>'
+'<td><input class="page-last" type="button" value=" >> " /></td>'
+'<td><input class="page-index" type="text" style="width:20px;"/><input class="page-go" type="button" value="go" /></td>'
+'<td><span class="page-totalCount">共'+totalCount+'条记录</span></td>'
+'<td><input id="currentPage" type="button" style="visibility:hidden;" /></td>'
+'<td><input id="totalCount" type="button" style="visibility:hidden;"/></td>'
+'</tr></tbody></table>';
panel.empty();
panel.append(html);
$('#currentPage').val('1');
$('#totalCount').val(pageCount());
$('input.page-first',panel).bind('click',selectPage('first'));
$('input.page-previous',panel).bind('click',selectPage('previous'));
$('input.page-next',panel).bind('click',selectPage('next'));
$('input.page-last',panel).bind('click',selectPage('last'));
$('input.page-go',panel).bind('click',selectPage('go'));
}
render();
$('input.page-first').click();
});
}
});
})(jQuery);
2.后台HandlerTest.ashx.cs
Code
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Text;
using App.Business;
namespace App.Handler
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class HandlerTest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string result = string.Empty;
if (context.Request.Params["getPageCount"] != null) result = GetRecordsCount();
if (context.Request.Params["pageIndex"] != null)
{
string pageindex = context.Request.Params["pageIndex"];
result = GetPageData(context.Request.Params["pageIndex"]);
}
context.Response.Write(result);
}
private string GetPageData(string p)
{
int pageIndex = int.Parse(p);
return DataTable2Json(StockStatBusiness.Instance.SelectByWhere(10, pageIndex, "sumdealmoney>10000").Tables[0]);
}
private string GetRecordsCount()
{
return StockStatBusiness.Instance.GetRecordCount("sumdealmoney>10000").ToString();
}
public static string DataTable2Json(DataTable dt)
{
StringBuilder jsonBuilder = new StringBuilder();
jsonBuilder.Append("{\"");
jsonBuilder.Append(dt.TableName.ToLower() == string.Empty ? "table" : dt.TableName.ToLower());
jsonBuilder.Append("\":[");
for (int i = 0; i < dt.Rows.Count; i++)
{
jsonBuilder.Append("{");
for (int j = 0; j < dt.Columns.Count; j++)
{
jsonBuilder.Append("\"");
jsonBuilder.Append(dt.Columns[j].ColumnName);
jsonBuilder.Append("\":\"");
jsonBuilder.Append(dt.Rows[i][j].ToString());
jsonBuilder.Append("\",");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("},");
}
jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
jsonBuilder.Append("]");
jsonBuilder.Append("}");
return jsonBuilder.ToString();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
3.页面呈现Pager.aspx
Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Pager.aspx.cs" Inherits="App.Pager" %>
<!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>AjaxPager</title>
<script src="../Scripts/jquery-1.2.3-intellisense.js" type="text/javascript"></script>
<script src="../Scripts/extend.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var totalCount = 0;
$.ajax({
type: "get",
dataType: "text",
url: "../Handler/HandlerTest.ashx",
data: "getPageCount=1",
async: false,
success: function(msg){
totalCount = parseInt(msg);
alert(totalCount);
}
});
$('#mypage').pager(totalCount,{
callback:function(page){
$("[@id=ready]").remove();
$("#load").show();
$.ajax({
type: "get",
dataType: "json",
url: "../Handler/HandlerTest.ashx",
data: "pageIndex=" + page,/
complete :function(){$("#load").hide();},
success: function(msg){//msg为返回的数据,在这里做数据绑定
$.each(msg.table, function(i, n){
var row = $("#template").clone();
row.find("#StockCode").text(n.StockCode);
row.find("#SumDealNum").text(n.SumDealNum);
row.find("#SumDealMoney").text(n.SumDealMoney);
row.find("#SumBargainExpense").text(n.SumBargainExpense);
row.find("#Profit").text(n.Profit);
row.find("#LeftDealNum").text(n.LeftDealNum);
row.attr("id","ready");//改变绑定好数据的行的id
row.appendTo("#datas");//添加到模板的容器中
});
$("[@id=ready]").show();
}
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="mypage" ></div>
<div>
<ul id="datas">
<li id="template">
<span id="StockCode">
StockCode
</span>/
<span id="SumDealNum">
SumDealNum
</span>/
<span id="SumDealMoney">
SumDealMoney
</span>/
<span id="SumBargainExpense">
SumBargainExpense
</span>/
<span id="Profit">
Profit
</span>/
<span id="LeftDealNum">
LeftDealNum
</span>
</li>
</ul>
</div>
<div id="load" style="right: 0px; position: absolute; top: 0px; background-color: red; display:none;">
LOADING.
</div>
</form>
</body>
</html>
这个实现只是初步方案,扩展方法和页面元素关联度太大,因此我准备做优化的方案,也请大家给我些更好的建议或实现方法。