1818IP-服务器技术教程,云服务器评测推荐,服务器系统排错处理,环境搭建,攻击防护等

当前位置:首页 - 网站技术 - asp - 正文

君子好学,自强不息!

ASP Cookies

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 带有键(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。下面的实例向您演示了如何做到这一点(请注意,下面的代码通过 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


本文来源:1818IP

本文地址:https://www.1818ip.com/post/422.html

免责声明:本文由用户上传,如有侵权请联系删除!

发表评论

必填

选填

选填

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。