Javascript--cookie

Source: Internet
Author: User

Cookie Basics in JavaScript

Pages are used to store information, such as logging in and remembering user names.

"Characteristics of cookies"

(1) Sharing a set of cookies on all pages of the same website;

(2) Limited quantity and size;

(3) Have a shelf life, expiration time (by JS Control);

(4) A cookie exists on the client.

"Cookies in JS use"

Document.cookie

"Set Cookies"

(1) Format: First name = value;

(2) will not be overwritten;

(3) Expiration Time: expires= time (use of Date object: odate=new date ());

For example:

var odate=New Date ();    // Get Time odate.setdate (odate.getdate () +30);     // setDate (): Set time document.cookie= "user=blue;expires=" +odate;   // Expires: Expiration time, here is 30 days document.cookie= "pass=123";  alert (document.cookie);

Get results:

(4) Package function

function Setcookie (name,value,iday) {     var odate=New  Date ();     Odate.setdate (Odate.getdate ()+iday);     Document.cookie=name+ ' = ' +value+ '; +expires ' +odate;} alert (Document.cookie);

Parameter meaning: Name: Custom Name

Value: Values of the first name

Iday: Expiry time

"Read Cookie"

String segmentation

 functionGetCookie (name) {//' username=abc; password=123456; aaa=111; bbb=222 '     varArr=document.cookie.split ('; ‘); varI=0; //arr->[' username=abc ', ' password=123456 ' ...]      for(i=0;i<arr.length;i++){         varArr2=arr[i].split (' = ')); //arr2->[' username ', ' abc ']         if(arr2[0]==name) {             returnArr2[1]; }     }     return‘‘; } Alert (GetCookie (' username '));

Get results:

"Delete Cookie"

function Removecookie (name) {    Setcookie (name,// Iday set to-1}

Javascript--cookie

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.