ASP Cookies
cookie 常用於識別用戶。

嘗試一下 - 實例
Welcome cookie
本例演示如何創建 Welcome cookie。
Cookie 是什麼?
cookie 常用用於識別用戶。cookie 是一種伺服器留在用戶電腦上的小檔。每當同一臺電腦通過流覽器請求頁面時,這臺電腦將會發送 cookie。通過 ASP,您能夠創建並取回 cookie 的值。
如何創建 Cookie?
"Response.Cookies" 命令用於創建 cookie。
注釋:Response.Cookies 命令必須出現在 <html> 標籤之前。
在下面的實例中,我們將創建一個名為 "firstname" 的 cookie,並將其賦值為 "Alex":
Response.Cookies("firstname")="Alex"
%>
向 cookie 分配屬性也是可以的,比如設置 cookie 的失效時間:
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>
如何取回 Cookie 的值?
"Request.Cookies" 命令用於取回 cookie 的值。
在下面的實例中,我們取回了名為 "firstname" 的 cookie 的值,並把值顯示到了頁面上:
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
輸出: Firstname=Alex
帶有鍵的 Cookie
如果一個 cookie 包含多個值的集合,我們就可以說 cookie 帶有鍵(Keys)。
在下面的實例中,我們將創建一個名為 "user" 的 cookie 集合。"user" cookie 帶有包含用戶資訊的鍵:
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
讀取所有的 Cookie
請閱讀下麵的代碼:
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
假設您的伺服器將上面所有的 cookie 傳給了某個用戶。
現在,我們需要讀取這些傳給某個用戶的所有的 cookie。下麵的實例向您演示了如何做到這一點(請注意,下麵的代碼通過 HasKeys 屬性檢查 cookie 是否帶有鍵):
<html>
<body>
<%
dim x,y
for each x in Request.Cookies
response.write("<p>")
if Request.Cookies(x).HasKeys then
for each y in Request.Cookies(x)
response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
response.write("<br>")
next
else
Response.Write(x & "=" & Request.Cookies(x) & "<br>")
end if
response.write "</p>"
next
%>
</body>
</html>
輸出:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:country=Norway
user:age=25
如果流覽器不支持 Cookie 該怎麼辦?
如果您的應用程式需要與不支持 cookie 的流覽器打交道,那麼您不得不使用其他的辦法在您的應用程式中的頁面之間傳遞資訊。這裏有兩種辦法:
1. 向 URL 添加參數
您可以向 URL 添加參數:
然後在 "welcome.asp" 檔中取回這些值,如下所示:
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>
2. 使用表單
您可以使用表單。當用戶點擊 Submit 按鈕時,表單會把用戶輸入傳給 "welcome.asp" :
First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>
然後在 "welcome.asp" 檔中取回這些值,如下所示:
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>