top
Loading...
ASP Cookies

ASP Cookies


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 是否帶有鍵):

<!DOCTYPE html>
<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 添加參數:

<a href="welcome.asp?fname=John&lname=Smith">Go to Welcome Page</a>

然後在 "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" :

<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>")
%>

北斗有巢氏 有巢氏北斗