ASP 饼干


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

输出:名字=亚历克斯



带钥匙的 Cookie

如果一个cookie包含多个值的集合,我们就说该cookie有Keys。

在下面的示例中,我们将创建一个名为 "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。下面的示例展示了如何执行此操作(请注意,下面的代码检查 cookie 是否具有带有 HasKeys 属性的键):

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

输出:

名字=亚历克斯

用户:名字=约翰
用户:姓氏=史密斯
用户:国家=挪威
用户:年龄=25


如果浏览器不支持 Cookie 怎么办?

如果您的应用程序处理不支持 cookie 的浏览器,则您将必须使用其他方法将信息从应用程序中的一个页面传递到另一个页面。有两种方法可以做到这一点:

1.给URL添加参数

您可以向 URL 添加参数:

<a href="welcome.html?fname=John&lname=Smith">Go to Welcome Page</a>

并检索 "welcome.html" 文件中的值,如下所示:

<%
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.html":

<form method="post" action="welcome.html">
First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>

检索 "welcome.html" 文件中的值,如下所示:

<%
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>