Writing and reading cookies using JavaScript

Source: Internet
Author: User

A cookie is the data stored on the user's local computer through a web browser. When the user accesses the web page again, the browser sends the data to the web page.

The most typical cookie is to determine whether a registered user has logged on to the website. The user may be prompted whether to keep the user information when entering the website for simplified login procedures, that is, "remember the password". These so-called memories are saved using cookies. Another important application scenario is "Shopping Cart processing". Users may choose different products on different pages of the same home within a period of time. The webpage writes the information to cookies, to extract information during payment.

In JS, we use the document. Cookie attribute to write and read cookies.

 

Cookie writing format: Document. Cookie = 'cookiename = '+ escape ('cookievalue') + '; expires =' + dataobj. togmtstring ()

View code

    Function  Writecookie (){
VaR Vdate = New Date ();
Document. Cookie = " Name = " + Escape ( ' Write cookie ' ) + ' ; Expires = ' + Vdate. settime (vdate. gettime () + 1 * 24 * 60 * 60 * 1000 ). Togmtstring ();
}
Function Readcookie (){
VaR Cookievalue = Document. Cookie;
VaR Start = Cookievalue. indexof ( ' Name = ' );
If (Start ! = - 1 ){
Start + = ' Name ' . Length + 1 ;
VaR End = Cookievalue. indexof ( ' ; ' , Start );
If (End = - 1 ){
Alert (Unescape (cookievalue. substring (start )));
}
Else {
Alert (Unescape (cookievalue. substring (START, end )));
}
}
}

 

 

Related Article

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.