Bộ sưu tập cookie ASP
❮ Tham chiếu đối tượng phản hồi hoàn chỉnh
Bộ sưu tập Cookie được sử dụng để đặt hoặc lấy các giá trị cookie. Nếu cookie không tồn tại, nó sẽ được tạo và lấy giá trị được chỉ định.
Lưu ý: Lệnh Response.Cookies phải xuất hiện trước thẻ <html>.
Cú pháp
Response.Cookies(name)[(key)|.attribute]=value
variablename=Request.Cookies(name)[(key)|.attribute]
Parameter | Description |
---|---|
name | Required. The name of the cookie |
value | Required for the Response.Cookies command. The value of the cookie |
attribute | Optional. Specifies information about the cookie. Can be one of the following parameters:
|
key | Optional. Specifies the key to where the value is assigned |
Các ví dụ
Lệnh "Response.Cookies" được sử dụng để tạo cookie hoặc đặt giá trị cookie:
<%
Response.Cookies("firstname")="Alex"
%>
Trong đoạn mã trên, chúng tôi đã tạo một cookie có tên "firstname" và gán giá trị "Alex" cho nó.
Cũng có thể chỉ định một số thuộc tính cho cookie, chẳng hạn như đặt ngày khi cookie sẽ hết hạn:
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2002#
%>
Bây giờ cookie có tên "firstname" có giá trị là "Alex" và nó sẽ hết hạn trên máy tính của người dùng vào ngày 10 tháng 5 năm 2002.
Lệnh "Request.Cookies" được sử dụng để lấy giá trị cookie.
Trong ví dụ bên dưới, chúng tôi truy xuất giá trị của cookie "firstname" và hiển thị nó trên một trang:
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
Đầu ra:
Firstname=Alex
Một cookie cũng có thể chứa một tập hợp nhiều giá trị. Chúng tôi nói rằng cookie có Chìa khóa.
Trong ví dụ dưới đây, chúng tôi sẽ tạo một bộ sưu tập cookie có tên là "người dùng". Cookie "người dùng" có các Khóa chứa thông tin về người dùng:
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
Đoạn mã dưới đây đọc tất cả cookie mà máy chủ của bạn đã gửi cho người dùng. Lưu ý rằng mã kiểm tra xem cookie có Khóa với thuộc tính HasKeys hay không:
<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>
%>
Đầu ra:
firstname=Alex
user:firstname=John
user:lastname=Smith
user:
country=Norway
user:
age=25
❮ Tham chiếu đối tượng phản hồi hoàn chỉnh