JS set cookies, delete cookies

Source: Internet
Author: User
Tags set cookie setcookie
js set cookies, delete cookies

There are a number of ways to set up cookies for JS.

The first: (This is the code of the official website)

<script>//Set cookie function Setcookie (CNAME, cvalue, exdays) {var d = new Date ();
    D.settime (D.gettime () + (exdays*24*60*60*1000));
    var expires = "expires=" +d.toutcstring ();
Document.cookie = cname + "=" + Cvalue + ";" + expires;
    //Get Cookie function GetCookie (CNAME) {var name = cname + ' = ';
    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);
    if (c.indexof (name)!=-1) return c.substring (Name.length, c.length);
} return "";}  
Clears the cookie function ClearCookie (name) {Setcookie (name, "",-1);
    function Checkcookie () {var user = GetCookie ("username");
    if (User!= "") {alert ("Welcome again" + user);
        else {user = prompt ("Please enter your name:", "");
        if (User!= "" && user!= null) {Setcookie ("username", user, 365); 
}} checkcookie (); </script>

The second type:

<script>
//js How to operate cookies!

Write Cookies
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 ());
 }
 
Read Cookies
function GetCookie (name)
{
    var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *)(;|$)");
 
    if (Arr=document.cookie.match (reg)) return
 
        (arr[2]);
    else return
        null;
}

Delete Cookies
function Delcookie (name)
{
    var exp = new Date ();
    Exp.settime (Exp.gettime ()-1);
    var cval=getcookie (name);
    if (cval!=null)
        document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}
Use
The example Setcookie (' username ', ' Darren ', ') 
alert (GetCookie ("username"));
</script>

A third example

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.