ASP Cookie
cookie 常用來對用戶進(jìn)行識別。
實(shí)例:
- Welcome cookie
- 如何創(chuàng)建歡迎 cookie。
什么是 Cookie?
cookie 常用來對用戶進(jìn)行識別。cookie 是一種服務(wù)器留在用戶電腦中的小文件。每當(dāng)同一臺電腦通過瀏覽器請求頁面時(shí),這臺電腦也會(huì)發(fā)送 cookie。通過 ASP,您能夠創(chuàng)建并取回 cookie 的值。
如何創(chuàng)建 cookie?
"Response.Cookies" 命令用于創(chuàng)建 cookie。
注意:Response.Cookies 命令必須位于 <html> 標(biāo)簽之前。
在下面的例子中,我們會(huì)創(chuàng)建一個(gè)名為 "firstname" 的 cookie,并向其賦值 "Alex":
<% Response.Cookies("firstname")="Alex" %>
向 cookie 分配屬性也是可以的,比如設(shè)置 cookie 的失效時(shí)間:
<% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2020# %>
如何取回 cookie 的值?
"Request.Cookies" 命令用于取回 cookie 的值。
在下面的例子中,我們?nèi)』亓嗣麨?"firstname" 的 cookie 的值,并把值顯示到了頁面上:
<% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %>
輸出:
Firstname=Alex
帶有鍵的 cookie
如果一個(gè) cookie 包含多個(gè)值的一個(gè)集合,我們就可以說 cookie 擁有鍵(Keys)。
在下面的例子中,我們會(huì)創(chuàng)建一個(gè)名為 "user" 的 cookie 集。"user" cookie 擁有包含用戶信息的鍵:
<% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Adams" Response.Cookies("user")("country")="UK" Response.Cookies("user")("age")="25" %>
讀取所有的 cookie
請閱讀下面的代碼:
<% Response.Cookies("firstname")="Alex" Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Adams" Response.Cookies("user")("country")="UK" Response.Cookies("user")("age")="25" %>
假設(shè)您的服務(wù)器將所有的這些 cookie 傳給了某個(gè)用戶。
現(xiàn)在,我們需要讀取這些 cookie。下面的例子向您展示如何做到這一點(diǎn)(請注意,下面的代碼會(huì)使用 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=Adams user:country=UK user:age=25
如何應(yīng)對不支持 cookie 的瀏覽器?
如果您的應(yīng)用程序需要和不支持 cookie 的瀏覽器打交道,那么您不得不使用其他的辦法在您的應(yīng)用程序中的頁面之間傳遞信息。這里有兩種辦法:
1. 向 URL 添加參數(shù)
您可以向 URL 添加參數(shù):
<a href="welcome.asp?fname=John&lname=Adams"> Go to Welcome Page </a>
然后在類似于下面這個(gè) "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. 使用表單
您還可以使用表單。當(dāng)用戶點(diǎn)擊提交按鈕時(shí),表單會(huì)把用戶輸入的數(shù)據(jù)提交給 "welcome.asp" :
<form method="post" action="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>") %>