Koleksi Cookies ASP

age=25

Koleksi Cookies digunakan untuk menetapkan atau mendapatkan nilai cookie. Jika cookie tidak wujud, ia akan dibuat dan diberikan nilai yang ditentukan.

Komen:Perintah Response.Cookies mesti berada di sebelum tag <html>.

Sintaks:

Response.Cookies(name)[(key)|.attribute]=value
variablename=Request.Cookies(name)[(key)|.attribute]
Parameter Penerangan
name Wajib. Nama cookie.
value Wajib (untuk perintah Response.Cookies). Nilai cookie.
attribute

Pilihan. Tentukan maklumat tentang cookie. Bisa menjadi salah satu daripada parameter di bawah ini.

  • Domain - hanya tulis; cookie hanya dikirim ke permintaan yang mencapai domén ini.
  • Expires - hanya tulis; tarikh tamat tempoh berlaku cookie. Jika belum ditentukan tarikh, cookie akan berakhir apabila sesi berakhir.
  • HasKeys - hanya baca; menentukan jika cookie memiliki key (ini adalah satu-satunya atribut yang dapat digunakan dengan perintah Request.Cookies)
  • Path - hanya tulis; jika diatur, cookie hanya dikirim ke permintaan yang mencapai jalur ini. Jika belum diatur, maka digunakan jalur aplikasi.
  • Secure - hanya tulis; menunjukkan jika cookie adalah selamat.
key Pilihan. Tentukan tempat pengaturan key.

Contoh

"Response.Cookies" perintah digunakan untuk membuat cookie atau menetapkan nilai cookie:

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

Dalam kod di atas, kami membuat cookie yang dinamakan "firstname" dan memberikannya nilai alex.

Juga boleh menetapkan sifat bagi cookie, seperti menetapkan masa tamat tempoh berlaku cookie:

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

现在,名为 "firstname" 的 cookie 的值是 "Alex",同时它在用户电脑中的失效日期是 2002 年 5 月 10 日。

"Request.Cookies" 命令用于取回 cookie 的值。

在以下例子中,我们取回了 cookie "firstname" 的值,并把它显示到页面上:

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

%>

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"
</html>

以下代码可读出所有服务器已向用户发送的 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 /")
    response.write "</p>"
  else
    Response.Write(x & "=" & Request.Cookies(x) & "<br />")
  end if
  end if
response.write "</p>"
</html>
next
</body>
</html>

%>

Output:
firstname=Alex
user:firstname=John
country=UK
user:lastname=Adams
country=UK
user:

age=25