Cookies are used to track website visitors and retain user preferences. Consider the following code:
<%
Response.Cookies("SweetCookie") = "true"
Response.Cookies("SweetCookie").Expires="December 31, 2004"
%>
The code above creates a cookie called SweetCookie on the user's computer. The cookie is set to expire at the end of 2004. If you want your cookie to expire when your visitor closes his browser, all you need to do is NOT to set the Expires property of Response.Cookies.
Reading cookies in ASP is as easier as writing them
<%
sCookie = Request.Cookies("SweetCookie")
%>
You can use cookies to determine if a visitor has been on your website before (returning visitor), and display customized greeting message depending on that:
<%
If Request.Cookies("SweetCookie") = "true" Then
sResponse = "Welcome returning visitor!"
Else
sResponse = "Welcome new visitor!"
Response.Cookies("SweetCookie") = "true"
Response.Cookies("SweetCookie").Expires="December 31, 2004"
End If
Response.Write sResponse
%>
Similiarly in ASP.NET, you can add cookies to the System.Web.HttpResponse.Cookies collection similar to the following example:
Response.Cookies("userName").Value = "patrick"
Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)
Dim aCookie As New HttpCookie("lastVisit")
aCookie.Value = DateTime.Now.ToString()
aCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(aCookie)
In Javascript, cookies can be created, read and erased by JavaScript. They are accessible through the property document.cookie. Though you can treat document.cookie as if it's a string, it isn't really, and you have only access to the name-value pairs.
document.cookie =
'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/';
To make things easier, we need the following functions to have full access to cookie:
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.