Latest web development tutorials

ASP Cookies collection

Response Object Reference Complete Response Object Reference

Cookies collection is used to set or get the value of the cookie. If the cookie does not exist, create it, and give it a predetermined value.

Note: Response.Cookies command must precede the <html> tag.

grammar

Response.Cookies(name)[(key)|.attribute]=value

variablename=Request.Cookies(name)[(key)|.attribute]

参数 描述
name 必需。cookie 的名称。
value 必需(对于 Response.Cookies 命令)。cookie 的值。
attribute 可选。规定有关 cookie 的信息。可以是下面的参数之一:
  • Domain - 只写。cookie 仅送往到达该域的请求。
  • Expires - 只写。cookie 的失效日期。如果没有规定日期,cookie 会在 session 结束时失效。
  • HasKeys - 只读。规定 cookie 是否拥有 key(这是唯一一个可与 Request.Cookies 命令使用的属性)。
  • Path - 只写。如果设置,cookie 仅送往到达此路径的请求。如果没有设置,则使用应用程序的路径。
  • Secure - 只写。指示 cookie 是否安全。
key 可选。规定在何处赋值的 key。


Examples

"Response.Cookies" command is used to create a cookie or set cookie values:

<%
Response.Cookies("firstname")="Alex"
%>

In the above code, we have created a directory named "firstname" the cookie, and assign it to "Alex".

You can also set the properties for the cookie, for example, you set the cookie expire:

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>

Now, the value named "firstname" of the cookie is "Alex", while its expiration date in the user's computer is May 10, 2002.

"Request.Cookies" command is used to retrieve a cookie value.

In the following example, we retrieve the cookie "firstname" value, and displays it on the page:

<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

Output:
Firstname=Alex

A cookie can contain more than one set of values. We have called cookie key.

In the following example, we want to create a cookie collection named "user" of. "User" cookie has contains information about the user's key:

<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

The following code can be read cookie has been sent by the user for all servers. Note that we use HasKeys property to determine whether the cookie has key:

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

Output:

firstname=Alex

user:firstname=John
user:lastname=Smith
user:
country=Norway
user:
age=25



Response Object Reference Complete Response Object Reference