jquery.pagination.js (經典分頁外掛).aspx + .ashx 處理程式)AjaxJson.aspx<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxJson.aspx.cs" Inherits="AjaxJson" %>
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery + Ajax + JSON 無刷新分頁</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="Styles/tablecloth.css" rel="stylesheet" type="text/css" />
<link href="Styles/pagination.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.pagination.js"></script>
<script type="text/javascript">
var pageIndex = 0; // 當前頁索引 (0-based)
var pageSize = 10; // 每頁筆數
$(function () {
InitTable(0); // 首次載入第 1 頁
// 初始化分頁外掛
$("#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);
}
// Ajax 請求資料並渲染表格
function InitTable(pageIndex) {
$.ajax({
type: "POST",
dataType: "json",
url: 'SupplyAJAX.aspx', // 一般處理程式或頁面
data: "type=show&random=" + Math.random() + "&pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize,
error: function () { alert('資料載入失敗'); },
success: function (data) {
// 清除現有資料列 (保留表頭)
$("#Result tr:gt(0)").remove();
var html = "";
$.each(data.data, function (index, item) {
html += "<tr><td>" + item.Id + "</td><td>" + item.Name + "</td><td>" + item.Sex + "</td></tr>";
});
$("#Result").append(html);
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="Result" cellspacing="0" cellpadding="0">
<tr><th>編號</th><th>姓名</th><th>性別</th></tr>
</table>
<div id="Pagination"></div>
</form>
</body>
</html>
AjaxJson.aspx.cs (取得總筆數)public partial class AjaxJson : System.Web.UI.Page
{
public string pageCount = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string url = "/SupplyAJAX.aspx";
string strResult = GetRequestJsonString(url, "type=getcount");
pageCount = strResult; // 總筆數供前端分頁外掛使用
}
}
// 後端發送 HTTP 請求取得 ashx 回傳資料
public static string GetRequestJsonString(string relativePath, string data)
{
string requestUrl = GetRequestUrl(relativePath, data);
try
{
WebRequest request = WebRequest.Create(requestUrl);
request.Method = "GET";
using (StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
return reader.ReadToEnd();
}
}
catch (Exception ex)
{
// 記錄日誌
return "0";
}
}
private static string GetRequestUrl(string relativePath, string data)
{
// 組合完整 URL 邏輯
return "https://" + HttpContext.Current.Request.Url.Authority + relativePath + "?" + data;
}
}
SupplyAJAX.aspx.cs (或 .ashx)public partial class SupplyAJAX : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string type = Request["type"];
if (type == "getcount")
{
// 查詢總筆數
int total = GetTotalCountFromDB();
Response.Write(total.ToString());
}
else if (type == "show")
{
int pageIndex = int.Parse(Request["pageIndex"]); // 1-based
int pageSize = int.Parse(Request["pageSize"]);
var list = GetPagedData(pageIndex, pageSize); // 回傳 List
// 手動序列化或使用 JavaScriptSerializer / Json.NET
var result = new { data = list };
Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(result));
}
Response.End();
}
// 模擬資料存取
private int GetTotalCountFromDB() { return 100; }
private List GetPagedData(int pageIndex, int pageSize)
{
// 實際應使用 SQL 分頁 (ROW_NUMBER / OFFSET FETCH)
return new List();
}
}
public class User { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } }
JsonConvert.SerializeObject 效能與容錯優於 JavaScriptSerializer。OFFSET ... ROWS FETCH NEXT ... ROWS ONLY,避免撈全表再切頁。{ success: bool, data: ..., message: "" } 結構,前端統一處理。此範例展示了經典 ASP.NET Web Forms 時代「jQuery + Ajax + JSON + 分頁外掛」的無刷新分頁完整實作。雖然套件版本較舊,但核心架構——前端分頁控制、非同步請求、後端分頁查詢、JSON 序列化、動態 DOM 渲染——在現代前後端分離架構中依然是基礎範式,理解其運作細節有助於技術遷移與維護舊系統。