I. What is Cookie
Cookie is a variable stored on the visitor's computer. Cookie is sent whenever the same computer requests a page through the browser. You can use JavaScript to create and retrieve cookie values.
For example, when we visit sina and other mailboxes, there will be an option to remind us whether to save the account and password. If yes, our account and password will be saved in the Cookie.
II. Instructions
The Cookie property of the document object can be used to read, create, modify and delete the cookie of the current document.
1. Return Cookie
The cookie of the current document can be returned by the following code:
document.write(document.cookie);
2. Create Cookie
Creating a function that can store the visitor's name in the Cookie variable in JSP:
function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}
c_name is the name, value is the value, and expiredays is the number of days to expire.
3. Check Cookie
The following function first checks whether there is a cookie in the document.cookie object.
If there are some cookies in the document.cookie object, it will continue to check whether the cookie we specified has been stored.
If the cookie we want is found, the value is returned, otherwise an empty string is returned.
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}