原理:首先创建服务器处理分页页面,要根据action参数来决定是返回数据总条数还是某页的数据.
GetCommentData.ashx:
<%@ WebHandler Language="C#" Class="GetDataCount" %>
using System;
using System.Web;
public class GetDataCount : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
var request = context.Request;
var response = context.Response;
string action =request["action"];
jiang_Db newdb = new jiang_Db();
if (action=="commentDataCount")//返回数据总条数
{
response.Write(newdb.ExecSql_Value("select count(*) from [comment]"));
}
else if (action=="commentDataPage")//返回分页数据
{
string page=request["page"];//页码
string pagesize = request["pagesize"];//每页显示条数
System.Data.OleDb.OleDbDataReader reader = newdb.Re_DataReader("select * from (select top " + pagesize + " * from (select top " + Convert.ToInt32(page) * Convert.ToInt32(pagesize) + " * from [comment] order by [id]) order by [id] desc) order by id");
response.Write(JSONHelper.GetJSON(reader,"comment"));//JSON序列化数据,并返回
newdb.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
这次用的是access数据库,不支持row_number() over()函数,所以要用下面这条比较复杂的sql语句.例如我们有11条数据,每页显示5条数据,所以要分三页,sql语句如下:
select * from
(select top 5 * from (select top 10 *
from [comment] order by [id]) order by [id] desc)
order by id
这条语句的原理是,比如要取6-10条,则先取前10条,再倒过来取前5条.
这里服务器如果返回数据如果是分页数据的话不可能是单条数据,一般用xml或者JSON来序列化格式后返回,这里使用自己写的JSON函数来直接把DataReader里的数据序列化并返回string,返回的结果如下格式:
JSONHelper类:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
public sealed class JSONHelper
{
/**/
///
/// 获取JSON字符串SqlDataReader
///
/// 值
/// 数据表名
///
public static string GetJSON(SqlDataReader drValue, string strTableName)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//sb.AppendLine("{");
//sb.AppendLine(" " + strTableName + ":{");
//sb.AppendLine(" records:[");
sb.AppendLine("[");
try
{
while (drValue.Read())
{
sb.Append(" {");
for (int i = 0; i < drValue.FieldCount; i++)
{
sb.AppendFormat("\"{0}\":\"{1}\",", drValue.GetName(i), drValue.GetValue(i));
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.AppendLine("},");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
drValue.Close();
}
sb.AppendLine(" ]");
//sb.AppendLine(" }");
//sb.AppendLine(" };");
return sb.ToString();
}
public static string GetJSON(OleDbDataReader drValue, string strTableName)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
//sb.AppendLine("{");
//sb.AppendLine(" " + strTableName + ":{");
//sb.AppendLine(" records:[");
sb.AppendLine("[");
try
{
while (drValue.Read())
{
sb.Append(" {");
for (int i = 0; i < drValue.FieldCount; i++)
{
sb.AppendFormat("\"{0}\":\"{1}\",", drValue.GetName(i), drValue.GetValue(i));
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
sb.AppendLine("},");
}
sb.Remove(sb.ToString().LastIndexOf(','), 1);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
drValue.Close();
}
sb.AppendLine(" ]");
// sb.AppendLine(" }");
// sb.AppendLine(" };");
return sb.ToString();
}
}
服务器页面算写好了,下面写客户端页面:
客户端要做的事情很简单,那就是发送一个带参数的请求给服务器,然后接受服务器返回的数据并用JQery的parseJSON()函数解析,再填充到页面即可.
<!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>
<title></title>
<style type="text/css">
#ulPage li
{
list-style-type: none;
float: left;
padding:5px;
}
</style>
<script src="../js/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
var pagesize = 5; //每页显示条数
$.post("GetCommentData.ashx", { "action": "commentDataCount" }, function(data, status) {
if (status == "success") {
var datacount = parseInt(data); //数据总条数
var pagenum; //页数
if (datacount % pagesize == 0) {
pagenum = datacount / pagesize;
}
else {
pagenum = datacount / pagesize + 1;
}
for (var i = 1; i <= pagenum; i++) {
var li = $("<li><a href=''>" + i + "</a></li>"); //添加li
$("#ulPage").append(li);
//添加分页点击事件///
li.click(function(e) {
e.preventDefault(); //阻止跳转
$("#sp1").text("数据总条数:" + datacount + ",每页显示" + pagesize + "条,当前第" + $(this).text() + "页 ");
$.post("GetCommentData.ashx", { "action": "commentDataPage", "page": $(this).text(), "pagesize": pagesize }, function(data, status) {
if (status == "success") {
$("#ulContent").empty(); //清空li
var comments = $.parseJSON(data); //JSON序列化数据
for (var i = 0; i < comments.length; i++) {
var comment = comments[i];
var li = $("<li>" + comment.name + " " + comment.uptime + " " + comment.content + "</li>");
$("#ulContent").append(li); //分别添加到页面上
}
}
});
});
//添加分页点击事件///
}
}
});
});
</script>
</head>
<body>
<ul id="ulContent">
</ul>
<span id="sp1"></span><ul id="ulPage">
</ul>
</body>
</html>
效果图: