javascript asp教程第九课--cookies

Response Cookies in General:

We'll start with the Response Cookies collection. I don't think it could be any easier. You simply put the name of the cookie in the argument. The corresponding value is a string. The only time it gets complicated is when you use keys (which I demonstrate below).

<%@LANGUAGE="JavaScript"%>
<%
var Tomorrow=new Date()
Tomorrow.setDate(Tomorrow.getDate() + 1)
myExpire = (Tomorrow.getMonth() + 1) + "/" + Tomorrow.getDate() 
myExpire += "/" + Tomorrow.getFullYear()

Response.Cookies("firstCookie") = "I like cookies."
Response.Cookies("firstCookie").Expires=myExpire

Response.Cookies("secondCookie") = "ASP Cookies Are Easy."
Response.Cookies("secondCookie").Expires=myExpire

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."
Response.Cookies("thirdCookie").Expires=myExpire
%>

<HTML>
We're just setting <%=Response.Cookies.Count%> cookies.<BR>
<A HREF="script09a.asp">Click Here</A> to retrieve these cookies.
</HTML>

Click Here to run the script in a new window.

Setting a cookie with ASP is pretty simple. The format is Response.Cookies("name")="value". That "value" can be either a JavaScript string or an ASP native type such as Request.Form("userEmail").

Response Cookie Keys:

If on the first page of your ASP application Response.Cookies("myOnlyCookie") is set, and subsequently on page two of your application Response.Cookies("myOnlyCookie") is reassigned a second value, then only the second value will remain. The first value is lost in this circumstance.

The solution is to either use multiple cookies or to use multiple Keys in the SAME cookie.

Response.Cookies("thirdCookie")("firstKey")="Here's the first Key."
Response.Cookies("thirdCookie")("secondKey")="Here's the second Key."

The Setting of one or more Keys is pretty simple. It follows this format: Response.Cookies("name")("key")="value". Again, the "value" can either be a JavaScript string or ASP native type. The advantage of using keys is that you can store multiple Key/Value pairs inside the very same cookie.

Request Cookies:

Generally you will find ASP cookie management to be far easier than Client Side JavaScript cookies. Down below is the script that retrieves the cookies.

<%@LANGUAGE="JavaScript"%>
<%
if (Response.Cookies.Count <= 0)
	{
	Response.Redirect("script09.asp")
	}
var firstCookie = Request.Cookies("firstCookie"); 
var secondCookie = Request.Cookies("secondCookie");
var thirdCookie2Keys = Request.Cookies("thirdCookie")("firstKey") 
thirdCookie2Keys += " " + Request.Cookies("thirdCookie")("secondKey");
%>
<HTML>
There are <%=Request.Cookies.Count%> Cookies.<BR>
1) <%=firstCookie%><BR>
2) <%=secondCookie%><BR>
3) <%=thirdCookie2Keys%><BR>
<A HREF="script09b.asp">Click Here</A> to see how we would sort cookies
if we didn't know their names.
</HTML>

      

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/2967.html