Koleksi Cookies ASP
Koleksi Cookies digunakan untuk menetapkan atau mendapatkan nilai cookie. Jika cookie tidak ada, buatnya dan berikan nilai yang ditentukan.
Komentar:Perintah Response.Cookies harus berada di bawah tag <html>.
Sintaks:
Response.Cookies(name)[(key)|.attribute]=value variablename=Request.Cookies(name)[(key)|.attribute]
Parameter | Deskripsi |
---|---|
name | Diperlukan. Nama cookie. |
value | Diperlukan (untuk perintah Response.Cookies). Nilai cookie. |
attribute | Pilihan. Tentukan informasi tentang cookie. Bisa menjadi salah satu parameter di bawah ini.
|
key | Pilihan. Tentukan tempat pengaturan key. |
Contoh
"Response.Cookies" perintah digunakan untuk membuat cookie atau menetapkan nilai cookie:
<% Response.Cookies("firstname")="Alex" %>
Dalam kod di atas, kami membuat cookie dengan nama "firstname" dan menetapkannya dengan nilai alex.
Juga boleh untuk menetapkan atribut cookie, seperti menetapkan masa tamat berlaku cookie:
<% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2002# %>
现在,名为 "firstname" 的 cookie 的值是 "Alex",同时它在用户电脑中的失效日期是 2002 年 5 月 10 日。
"Request.Cookies" 命令用于取回 cookie 的值。
在下面的例子中,我们取回了 cookie "firstname" 的值,并把它显示到页面上:
<% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %>
Output:
Firstname=Alex
一个 cookie 可以包含一个多值的集合。我们称之为 cookie 拥有 key 。
在下面的例子中,我们要创建一个名为 "user" 的 cookie 集合。"user" cookie 拥有包含有关用户信息的 key 。
<% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Adams" Response.Cookies("user")("country")="UK" Response.Cookies("user")("age")="25" %>
下面的代码可读出所有服务器已向用户发送的 cookie 。请注意,我们使用了 HasKeys 属性来判断 cookie 是否拥有 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=Adams user: country=UK user: age=25