用 DW + ASP 做 dynamically 頁面時,預設的分頁只有「首頁、上一頁、下一頁、末頁」四顆按鈕,使用者完全不知道自己在第幾頁、還有幾頁。以下示範如何改成完整的數字型分頁。
頁尾顯示成:第N頁[共*頁] << 1 2 3 4 5 6 7 8 9 10 >>
在 DW 中綁定記錄集後,程式碼頁會自動產生類似下面的內容:
<%
Dim Recordset1
Dim Recordset1_numRows
Set Recordset1 = Server.CreateObject("ADODB.Recordset")
Recordset1.ActiveConnection = MM_資料庫名稱_STRING
Recordset1.Source = "SELECT * FROM 表名"
Recordset1.CursorType = 0
Recordset1.CursorLocation = 2
Recordset1.LockType = 1
Recordset1.Open()
Recordset1_numRows = 0
%>
<%
Dim I
Dim RPP
Dim PageNo
I = 1
RPP = 50
PageNo = CInt(Request("PageNo")) ’ 以上為新增部分
Dim Recordset1
Dim Recordset1_numRows
Set Recordset1 = Server.CreateObject("ADODB.Recordset")
Recordset1.ActiveConnection = MM_資料庫名稱_STRING
Recordset1.Source = "SELECT * FROM 表名"
Recordset1.CursorType = 1 ’ 原本為 0,需改為 1
Recordset1.CursorLocation = 2
Recordset1.LockType = 1
Recordset1.Open()
Recordset1_numRows = 0
接著在這段之後補上分頁邏輯:
Recordset1.PageSize = RPP If PageNo <= 0 Then PageNo = 1 If PageNo > Recordset1.PageCount Then PageNo = Recordset1.PageCount Recordset1.AbsolutePage = PageNo
第一,游標類型要改。CursorType 從 0 改成 1。這是能否分頁的關鍵——只有動態游標才支援 PageSize 與 AbsolutePage 這類屬性。
第二,設定每頁筆數。RPP 就是每頁顯示的記錄數(本例為 50),記得先對使用者傳入的 PageNo 做範圍檢查,避免超出總頁數。
第三,輸出頁碼資訊。用一個簡單的副程式寫出目前頁數與總頁數:
Sub ShowPageInfo(tPageCount, cPageNo) Response.Write "第" & cPageNo & "頁[共" & tPageCount & "頁]" End Sub
再寫一個副程式產生頁碼連結。核心邏輯是「一次顯示固定數量的頁碼」:先設 NaviLength = 10 代表要顯示幾個數字,再用除法與餘數算出起始頁與結束頁,最後用迴圈輸出連結。
Sub ShowPageNavi(tPageCount, cPageNo) If cPageNo < 1 Then cPageNo = 1 If tPageCount < 1 Then tPageCount = 1 If cPageNo > tPageCount Then cPageNo = tPageCount Dim NaviLength NaviLength = 10 ’ 顯示的數字連結個數 Dim I, StartPage, EndPage StartPage = (cPageNo \ NaviLength) * NaviLength + 1 If (cPageNo Mod NaviLength) = 0 Then StartPage = StartPage - NaviLength EndPage = StartPage + NaviLength - 1 If EndPage > tPageCount Then EndPage = tPageCount If StartPage > 1 Then Response.Write "<a class=""pageNavi"" href=""?PageNo=" & (cPageNo - NaviLength) & """><<</a> " Else Response.Write "<font color=""#CCCCCC""><<</font> " End If For I = StartPage To EndPage ’ 逐頁輸出頁碼連結,目前頁可加上特殊樣式 Next End Sub
最後在頁面的適當位置呼叫這兩個副程式,並在記錄集迴圈中加上 AbsolutePage 的定位即可。
第一,用 AbsolutePage 定位屬於伺服器端分頁,資料量大時仍會把整份記錄集載入記憶體。若處理的是數萬筆資料,改用 SQL 的 TOP 搭配 WHERE 條件做真正的「只取這一頁」會有效率得多。
第二,PageNo 一定要經過 CInt 轉型並做範圍檢查,否則使用者隨便改網址參數就可能讓頁面丟出錯誤。