ASP Cookies
Cookie 常用于识别用户。
更多示例
欢迎 Cookie
如何创建欢迎 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 具有键。
在下面的示例中,我们将创建一个名为 "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">转到欢迎页面</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. 使用表单
您可以使用表单。当用户单击提交按钮时,表单会将用户输入传递到 "welcome.asp"
<form method="post" action="welcome.asp">
名字: <input type="text" name="fname" value="">
姓氏: <input type="text" name="lname" value="">
<input type="submit" value="提交">
</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>")
%>