先看效果图:
实现原理很简单,使用了jquery.pagination这个插件,每当点击页码时异步去服务器去取该页的数据,简单介绍如下:
一、数据库表结构:很简单 就四个字段 分别是news_id news_title news_time news_readtimes
二、前台页面代码:
<head runat="server">
<title>jquery无刷新分页</title>
<link href="styles/common.css" rel="stylesheet" type="text/css" />
<link href="styles/paging.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="scripts/jquery.pagination.js" type="text/javascript"></script>
<script type="text/javascript">
var pageindex = 0;
var pagesize = 3;
$(function() {
inittable(0);
$("#pagination").pagination(<%=pagecount %>, {
callback: pagecallback,
prev_text: '上一页',
next_text: '下一页',
items_per_page: pagesize,
num_display_entries: 6,//连续分页主体部分分页条目数
current_page: pageindex,//当前页索引
num_edge_entries: 2//两侧首尾分页条目数
});
//翻页调用
function pagecallback(index, jq) {
inittable(index);
}
//请求数据
function inittable(pageindex) {
$.ajax({
type: "post",
datatype: "text",
url: 'ajax/pagerhandler.ashx',
data: "pageindex=" + (pageindex + 1) + "&pagesize=" + pagesize,
success: function(data) {
$("#result tr:gt(0)").remove();//移除id为result的表格里的行,从第二行开始(这里根据页面布局不同页变)
$("#result").append(data);//将返回的数据追加到表格
}
});
}
});
</script>
</head>
<form id="form1" runat="server">
<center>
<table id="result" border="1" cellpadding="5" style="border-collapse: collapse; margin:20px;
border: solid 1px #85a8be;width:60%">
<tr>
<th style="width: 10%">
id
</th>
<th style="width: 60%">
标题
</th>
<th style="width: 20%">
更新时间
</th>
<th style="width: 10%">
点击量
</th>
</tr>
</table>
<div id="pagination" class="paging">
</div>
</center>
</form>
三、页面后台文件
这里主要是获取记录总数:
public string pagecount = string.empty;//总条目数
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
pagecount = new news().getnewscount();
}
}
四、最主要的是ajax处理程序:pagerhandler.ashx
public class pagerhandler : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
string str = string.empty;
int pageindex = convert.toint32(context.request["pageindex"]);
int size = convert.toint32(context.request["pagesize"]);
if (pageindex == 0)
{
pageindex = 1;
}
int count = 0;
news n = new news();
list<news> list = n.getnewslist(pageindex, size, ref count);
stringbuilder sb = new stringbuilder();
foreach (news p in list)
{
sb.append("<tr><td>");
sb.append(p.news_id);
sb.append("</td><td>");
sb.append("<a href='#'>"+p.news_title+"</a>");
sb.append("</td><td>");
sb.append(p.news_time);
sb.append("</td><td>");
sb.append(p.news_readtimes);
sb.append("</td></tr>");
}
str = sb.tostring();
context.response.write(str);
}
public bool isreusable
{
get
{
return false;
}
}
}
更多jquery+ajax无刷新分页的实例代码。
