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
}
}
}