Create and store cookies in javascript

Source: Internet
Author: User

1. Create a cookie
Js Code
Function setCookie (c_name, value, expiredays) // The parameter is name, value, and expiration date.
{
Var exdate = new Date ()
Exdate. setDate (exdate. getDate () + expiredays) // convert the number of days to a valid date.
Document. cookie = c_name + "=" + escape (value) +
(Expiredays = null )? "": "; Expires =" + exdate. toGMTString () // Save the name, value, and expiration date to the cookie object.
}
 
 
2. Create a function to check whether a cookie exists.
Js Code
Function getCookie (c_name) // obtain the name in the cookie
{
If (document. cookie. length> 0) // determines whether the cookie exists.
{
C_start = document. cookie. indexOf (c_name + "=") // the first occurrence location of the name obtained from the cookie
If (c_start! =-1) // indexOf () subscript starts from 0
{
C_start = c_start + c_name.length + 1
C_end = document. cookie. indexOf (";", c_start)
If (c_end =-1) c_end = document. cookie. length // The subscript is-1.
Return unescape (document. cookie. substring (c_start, c_end ))
// The unescape () function can decode strings encoded by escape ().
// The substring () method is used to extract characters that are intermediate between two specified subscripts.
 
}
}
Return ""
}
 
 
 
3. Create a function: If the cookie exists, the welcome xxx is displayed; otherwise, the prompt box prompts the user to enter the name.
Js Code
Function checkCookie ()
{
Username = getCookie ('username') // obtain the name in the cookie
If (username! = Null & username! = "") // Determines whether the name is null
{Alert ('Welcome again '+ username + '! ')}
Else
{
Username = prompt ('Please enter your name :',"")
If (username! = Null & username! = "")
{
SetCookie ('username', username, 365) // The setcookie () function sends an HTTP cookie to the client.
Cookie name, cookie value, and cookie Validity Period
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.