ASP Cookies
cookie 常用于識(shí)別用戶。

嘗試一下 - 實(shí)例
Welcome cookie
本例演示如何創(chuàng)建 Welcome cookie。
Cookie 是什么?
cookie 常用用于識(shí)別用戶。cookie 是一種服務(wù)器留在用戶計(jì)算機(jī)上的小文件。每當(dāng)同一臺(tái)計(jì)算機(jī)通過(guò)瀏覽器請(qǐng)求頁(yè)面時(shí),這臺(tái)計(jì)算機(jī)將會(huì)發(fā)送 cookie。通過(guò) ASP,您能夠創(chuàng)建并取回 cookie 的值。
如何創(chuàng)建 Cookie?
"Response.Cookies" 命令用于創(chuàng)建 cookie。
注釋:Response.Cookies 命令必須出現(xiàn)在 <html> 標(biāo)簽之前。
在下面的實(shí)例中,我們將創(chuàng)建一個(gè)名為 "firstname" 的 cookie,并將其賦值為 "Alex":
Response.Cookies("firstname")="Alex"
%>
向 cookie 分配屬性也是可以的,比如設(shè)置 cookie 的失效時(shí)間:
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>
如何取回 Cookie 的值?
"Request.Cookies" 命令用于取回 cookie 的值。
在下面的實(shí)例中,我們?nèi)』亓嗣麨?"firstname" 的 cookie 的值,并把值顯示到了頁(yè)面上:
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
輸出: Firstname=Alex
帶有鍵的 Cookie
如果一個(gè) cookie 包含多個(gè)值的集合,我們就可以說(shuō) cookie 帶有鍵(Keys)。
在下面的實(shí)例中,我們將創(chuàng)建一個(gè)名為 "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
請(qǐng)閱讀下面的代碼:
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
假設(shè)您的服務(wù)器將上面所有的 cookie 傳給了某個(gè)用戶。
現(xiàn)在,我們需要讀取這些傳給某個(gè)用戶的所有的 cookie。下面的實(shí)例向您演示了如何做到這一點(diǎn)(請(qǐng)注意,下面的代碼通過(guò) 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 該怎么辦?
如果您的應(yīng)用程序需要與不支持 cookie 的瀏覽器打交道,那么您不得不使用其他的辦法在您的應(yīng)用程序中的頁(yè)面之間傳遞信息。這里有兩種辦法:
1. 向 URL 添加參數(shù)
您可以向 URL 添加參數(shù):
然后在 "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)擊 Submit 按鈕時(shí),表單會(huì)把用戶輸入傳給 "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>")
%>