JQuery与JSon实现的无刷新分页代码
如图
而无刷新分页可以解决这个问题,上面播放着视频,下面我点下一页看着评论,现在大部分的网站都是无刷新分页。
源码如下(我是采用一页显示10条记录):
需要四个文件
一个实体类文件 CategoryInfoModel.cs
一个SqlHelper SQLHelper.cs
一个AJAX服务端处理程序 PagedService.ashx
一个客户端调用页面 WSXFY.htm
CategoryInfoModel.cs和SQLHelper.cs我就不写了,都知道是什么文件
PagedService.ashx 代码如下
代码如下:
using System.Web.Script.Serialization;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string strAction = context.Request["Action"];
//取页数
if (strAction == "GetPageCount")
{
string strSQL = "SELECT COUNT(*) FROM CategoryInfo";
int intRecordCount = SqlHelper.ExecuteScalar(strSQL);
int intPageCount = intRecordCount / 10;
if (intRecordCount % 10 != 0)
{
intPageCount++;
}
context.Response.Write(intPageCount);
}//取每页数据
else if (strAction == "GetPageData")
{
string strPageNum = context.Request["PageNum"];
int intPageNum = Convert.ToInt32(strPageNum);
int intStartRowIndex = (intPageNum - 1) * 10 + 1;
int intEndRowIndex = (intPageNum) * 10 + 1;
string strSQL = "SELECT * FROM ( SELECT ID,CategoryName,Row_Number() OVER(ORDER BY ID ASC) AS rownum FROM CategoryInfo) AS t";
strSQL += " WHERE t.rownum >= " + intStartRowIndex + " AND t.rownum <= " + intEndRowIndex;
DataSet ds = new DataSet();
SqlConnection conn = SqlHelper.GetConnection();
ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, strSQL);
List<CategoryInfoModel> categoryinfo_list = new List<CategoryInfoModel>();//定义实体集合
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
CategoryInfoModel categoryinfo = new CategoryInfoModel();
categoryinfo.CategoryInfoID = Convert.ToInt32(ds.Tables[0].Rows[i]["ID"]);
categoryinfo.CategoryName = ds.Tables[0].Rows[i]["CategoryName"].ToString();
categoryinfo_list.Add(categoryinfo);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
context.Response.Write(jss.Serialize(categoryinfo_list));//序列化实体集合为javascript对象
}
}
<head>
<title>无刷新分页</title>
<script type="text/javascript" src="../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$(function () {
$.post("PagedService.ashx", { "Action": "GetPageCount" }, function (response, status) {
for (var i = 1; i <= response; i++) {
var td = $("<td><a href=''>" + i + "</a></td>");
$("#trPage").append(td);
td.click(function (e) {
e.preventDefault(); //不要导向链接
$.post("PagedService.ashx", { "Action": "GetPageData", "PageNum":$(this).text() }, function (response, status) {
var categorys = $.parseJSON(response);
$("#ulCategory").empty();
for (var i = 0; i < categorys.length; i++) {
var category = categorys[i];
var li = $("<li>" + category.CategoryInfoID + "-" + category.CategoryName + "</li>");
$("#ulCategory").append(li);
}
});
});
}
});
});
</script>
</head>
<body>
<ul id="ulCategory"></ul>
<table>
<tr id="trPage">
</tr>
</table>
</body>
</html>
效果如下(页面好不好看取决于你画DOM 的水平了,我这里只是简单的画了画)