傳統分頁每換一頁就整頁重載,正在播放的影片中斷、輸入到一半的內容消失。無刷新分頁正是為了解決這個問題——如今大部分網站都已改採這種做法。

以下示例以「每頁顯示 10 筆」為例,需要四個部分:一個實體類別 CategoryInfoModel.cs、一個資料存取輔助類別 SQLHelper.cs、一個 Ajax 服務端處理程式 PagedService.ashx,以及一個呼叫用的頁面 WSXFY.htm。前兩者是基礎設施,這裡直接看後兩者。
用 Action 參數區分「取總頁數」與「取該頁資料」兩種請求,這是無刷新分頁最乾淨的切法:
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") {
int intPageNum = Convert.ToInt32(context.Request["PageNum"]);
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 = 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)); // 序列化實體集合
}
}
分頁的數學很直觀:起始列 = (頁碼 - 1) × 每頁筆數 + 1。SQL 則用 Row_Number() 先做視窗排序再篩範圍,這是 SQL Server 上常見的做法。
$(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];
$("#ulCategory").append($("<li>" + category.CategoryInfoID + "-" + category.CategoryName + "</li>"));
}
});
});
}
});
});
<body>
<ul id="ulCategory"></ul>
<table><tr id="trPage"></tr></table>
</body>
e.preventDefault() 這一行是重點:頁碼是用 <a href=''> 產生的,若不阻止預設行為,點擊會導致頁面跳轉,前面所有努力就白費了。
效果如下(外觀取決於你切 DOM 的功夫,這裡只是簡單畫了畫):

click 綁定的,改用事件代理 $('#trPage').on('click', 'a', handler) 只需綁一次。<li> 時,若 CategoryName 可能含特殊字元,應改用 .text() 設定文字。