變數是儲存資料的容器,理解其宣告方式、作用域與生命週期是 ASP 開發的基石。
<%
Dim name
name = "Donald Duck"
Response.Write("My name is: " & name)
%>
Dim 宣告區域變數。<%
Dim fname(5), i
fname(0) = "George"
fname(1) = "John"
fname(2) = "Thomas"
fname(3) = "James"
fname(4) = "Adrew"
fname(5) = "Martin"
For i = 0 To 5
Response.Write(fname(i) & "
")
Next
%>
<%
For i = 1 To 6
Response.Write("Header " & i & " ")
Next
%>
<%
Dim h
h = Hour(Now())
Response.Write("" & Now() & " (北京時間)
")
If h < 12 Then
Response.Write("Good Morning!")
Else
Response.Write("Good day!")
End If
%>
<%@ language="javascript" %>
<%
var d = new Date();
var h = d.getHours();
Response.Write("" + d + " (北京時間)
");
if (h < 12) Response.Write("Good Morning!");
else Response.Write("Good day!");
%>
| 宣告位置 | 生命週期 | 可存取範圍 |
|---|---|---|
| 程序/函式外部 (Script 區塊) | 頁面請求期間 | 該 ASP 檔案所有程式碼 (含 Include 檔) |
| 程序/函式內部 | 程序執行期間 | 僅該程序內部 |
| Session 變數 | Session 存活期間 (預設 20 分鐘無操作) | 同一用戶、同一應用程式所有頁面 |
| Application 變數 | 應用程式存活期間 (直到 IIS 重啟) | 所有用戶、所有頁面 |
<%
' 寫入
Session("UserName") = "Admin"
Session("LoginTime") = Now()
' 讀取
If Session("UserName") <> "" Then
Response.Write "歡迎," & Session("UserName")
End If
' 移除
Session.Remove("UserName")
' 或清空全部
Session.Abandon()
%>
<%
Application.Lock
Application("TotalVisits") = Application("TotalVisits") + 1
Application.UnLock
Response.Write "總瀏覽次數:" & Application("TotalVisits")
%>
最佳實務: 能用區域變數不用全域;需跨頁共用用 Session;全站統計用 Application (並配合 Lock);大型系統建議改用資料庫/Redis 取代 Application。