JS cookie operations (compatible with Chinese)

Source: Internet
Author: User
Tags set cookie

First, two methods are provided. One is to store cookies and the other is to retrieve cookies. This method can be used to store cookies compatible with Chinese characters.

 Function  Get_cookie (name ){  VaR Start = Document. Cookie. indexof (name + "=" );  VaR Len = start + name. Length + 1 ;  If ((! Start) & (name! = Document. Cookie. substring (0, name. Length ))) Return   Null  ;  If (START =-1) Return  Null  ;  VaR End = Document. Cookie. indexof (";" , Len );  If (END =-1) End = Document. Cookie. length;  Return  Decodeuri (document. Cookie. substring (Len, end ));}  Function  Set_cookie (name, value, expires, path, domain, secure) {expires = Expires * 60*60*24*1000 ;  VaR Today =New  Date ();  VaR Expires_date = New Date (today. gettime () + (Expires ));  VaR Cookiestring = Name + "=" + decodeuricomponent (value) /*  * Encodeuricomponent (value) seems to be OK *  */ + (Expires) ? "; Expires =" + expires_date.togmtstring (): "") + (PATH) ? "; Path =" + path: "") +(Domain) ? "; Domain =" + domain: "") + (Secure) ? "; Secure ":"" ); Document. Cookie = Cookiestring ;} 

When you want to store cookies, call the set_cookie function,

Set_cookie ("dynewform_name", zhuname, 36500 );

In this example, "dynewform_name" is the name of the Set cookie, zhuname is the value of the cookie name, And 36500 is the storage cycle, which is sufficient for general cookie operations.

Other input parameters are not explained,

When the stored cookie is called, The get_cookie function is called.

VaRNameone = get_cookie ("dynewform_name ");
Alert (nameone) // ==> zhuname

In this way, the cookie value dynewform_name is obtained. Sometimes, if the value is Chinese, decodeuricomponent is required.

That is:

VaR new_nameone = decodeuricomponent (nameone );

Write is not necessarily correct, but it is basically available ~


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.