Javascript read/write cooks

Source: Internet
Author: User
Tags setcookie
Don't try. I don't know if it's easy to use.
 
Function getcookie (name) // The cookie function {var arr = document. cookie. match (New Regexp ("(^ |)" + name + "= ([^;] *) (; | $)"); If (Arr! = NULL) return Unescape (ARR [2]); return NULL;} function setcookie (name, value) // two parameters, one is the name of the cookie, one is the value {var days = 1; // This cookie will be saved for 30 days var exp = new date (); // new date ("December 31,999 8"); exp. settime (exp. gettime () + days * 24x60*60*1000); document. cookie = Name + "=" + escape (value) + "; expires =" + exp. togmtstring ();}
Correct use of JavaScript cookies function getcookies (name)
{
VaR arr = document. cookie. match (New Regexp (& quot; (^ |) & quot; + name + & quot; = ([^;] *) (;|$) & quot ;));
If (Arr! = NULL) return Unescape (ARR [2]); Return & #039; & #039 ;;
}
Function setcookie (name, value, expires,

Function getcookies (name)
{
VaR arr = Document. Cookie. Match (New Regexp ("(^ |)" + name + "= ([^;] *) (; | $ )"));
If (Arr! = NULL) return Unescape (ARR [2]); Return '';
}
Function setcookie (name, value, expires, path, domain, secure)
{
VaR livedate = new date ();
Expires = livedate. settime (livedate. gettime () + expires * 60*1000); // millisecond
// Expires = new date (). gettime () + expires * 60000); // By minute
Document. Cookie = Name + "=" + escape (value) +
(Expires )? "; Expires =" + expires: "") +
(PATH )? "; Path =" + path: "") +
(Domain )? "; Domain =" + domain: "") +
(Secure )? "; Secure ":"");
}

The following online materials are available:
-----------------
JS cookie Summary
FSO is required recentlyCompositionTo save the path of the last file opened by the user using js to manipulate the cookie. It is found that there are some differences between using js to operate the cookie and using the server language to operate the cookie, there are still many small details that need to be noted. If used, it may lead to many unexpected results. When I encountered a problem, I checked a lot of information on the Internet and found that many of them simply introduced how JS operates cookies in a theoretical way. However, I found that this is not the case in some places. Below I have summarized some of my experiences in using js to operate cookies.

Using js to manipulate cookies is the cookie object under the document object. In fact, document. Cookie is a string,
Therefore, we can use all the methods of the string just like using a string, except that the string requires a format (Key = value) to set the cookie example.CodeAs follows:

Document. Cookie = "Key = escape (value )";

The cookie value cannot contain semicolons (;), commas (,), equal signs (=), and spaces. It is easy to do this in the cookie name, but the value to be saved is uncertain. How can we store these values? The method is encoded using the escape () function. It can represent some special symbols in hexadecimal notation. For example, spaces are encoded as "20%", which can be stored in cookie values, in addition, this solution can avoid Chinese garbled characters. The escape method is used on the value. When the value is set, you must use Unescape (value) to transcode the value.

If you want to set multiple cookies, you need to use this method multiple times. The correct setting method is as follows:
Document. Cookie = "Key = escape (value )";
Document. Cookie = "key1 = escape (value1 )"
Instead
Document. Cookie = "Key = escape (value); key1 = escape (value1 )";

To retrieve the cookie value, you can directly call document. cookie. If there are multiple values, multiple values are separated by semicolons (;), and each value is separated by equal sign (=), we can first use semicolons (;) split, and then split by equal sign (= ). Then compare the key value cyclically. If the key is equal, the value is taken out. Note that if there are multiple values, remove one space before the key value of the second value. The following is a sample code for obtaining cookies.

Function getcookie (key ){
VaR acookie = Document. Cookie. Split (";");
For (VAR I = 0; I <acookie. length; I ++ ){
VaR acrumb = acookie [I]. Split ("= ");
If (Key = acrumb [0]. Replace (/^ \ s * | \ s * $ /,"")){
Return Unescape (acrumb [1]);
}
}
}

After the previous sample code sets a cookie on a page, it can be obtained on this page, but the cookie exists. Generally, cookies are stored in the C: \ Documents ents and Settings \ Administrator \ Local Settings \ Temporary Internet Files directory. However, after deleting all the files in this folder, we can obtain the cookie and access it. After the browser is closed, you can obtain the cookie after you open the browser again. How long is the default cookie lifetime. How can I clear cookies. Sorry, I don't know where to save it, but after logging out or restarting, the cookie will be destroyed. I personally think this is a bug in designing JS cookies, because it is unfriendly for users to promptly clear cookies in one way. We can pass an Expires attribute when setting a cookie. This attribute is used to set the cookie survival time. The sample code for setting the cookie lifetime is as follows:

VaR livedate = new date ();
Livedate. settime (livedate. gettime () + 3*24*60*60*1000 );
Document. Cookie = "name = test; expires =" + livedate. togmtstring ();
The code above sets the cookie name to survive for three days. The cookie deletion value is to set an expiration time for expires. The sample code is as follows:
VaR livedate = new date ();
Livedate. settime (livedate. gettime ()-10000 );
Document. Cookie = "name = test; expires =" + date. togmtstring ();

However, it is interesting that after the expires attribute is set, the files that store cookies are generated in the C: \ Documents and Settings \ Administrator \ Local Settings \ Temporary Internet Files directory. After deleting the file, we found that the cookie is indeed destroyed. This is in line with our requirements. Therefore, we recommend that you set the expires attribute when setting cookies in JS. Normally, we should specify how long the cookie will survive when we use cookies.

Next, let's talk about the scope of JS cookie operations. By default, the scope of JS cookie operations is directory-level, that is, the cookie set under the current directory, this cookie can be accessed by all files in the current directory and all subdirectories in this directory, for example, the cookie set in http: // localhost: 8090/apptest/AAA/testcookie.html, all files in the http: // localhost: 8090/apptest/AAA/directory and http: // localhost: all files under 8090/apptest/AAA/BBB/can access this cookie, while in http: // localhost: the cookie cannot be accessed by files in the 8090/apptest/directory. When a cookie is set, a path attribute can change the valid access path of the cookie. However, currently, only one parameter "/" can be set in path, which indicates the root path. The sample code is as follows:

Document. Cookie = "Key = escape (value); Path = /";

If Path = "/" is set, no matter which path the cookie is set: 8090/apptest/
and all directories and subdirectories can access this cookie. theoretically, if Path = "\ AAA" is set, the cookie should be accessible under the AAA directory and all subdirectories under the AAA directory, however, this function is not actually implemented. I think this is also a bug in JS cookie implementation. Note that two cookies with the same name are set, for example, http: // localhost: 8090/apptest/AAA, if the path is set to "/" and the other cookie does not contain the path parameter, two cookie values with the same name are accessed at http: // localhost: 8090/apptest/AAA, however, if the path is http: // localhost: 8090/apptest/, you can only access the global cookie value. However, there is no way to distinguish between them by path. The second thing to note is to delete the cookie. If the cookie is set with the path attribute, you must add the path attribute When deleting the cookie. Otherwise, the cookie value set in the current directory is deleted.

In addition, when setting cookies, you can also set two attributes: domain and secure. Domain indicates setting the Cookie Access domain. Below I will give the basic domain theory.
For example, www.google.com and gmail.google.com are two different host names. By default, cookies created on one host cannot be accessed on the other, but can be controlled by the domain parameter. The syntax format is as follows:
Document. Cookie = "name = value; domain = cookiedomain ";
Take Google as an example. To achieve cross-host access, you can write as follows:
Document. Cookie = "name = value; domain = .google.com ";
In this way, all hosts under Google.com can access this cookie. Because I have never tested or used this parameter, if you want to use this parameter, you can refer to the theoretical section above.

Secure indicates whether the cookie is secure. If this attribute is set, only the HTTPS protocol can be used to access
This cookie.

The complete cookie format is provided below
Name = [; expires =] [; domain =] [; Path =] [; secure]
Name = <value> [; expires = <date>] [; domain = <domain>] [; Path = <path>] [; security]


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.