Html learning-setting and retrieving cookies in Javascript
Cookies
Cookies, sometimes in the form of Cookies, are the data (usually encrypted) stored on the user's local terminal for some websites to identify users and track sessions ).
Cookies
I also learned Cookies soon. So first write something simple.
Cookies are easy to set. Generally, each domain name has its own Cookies to save some simple data and user logon status.
Cookies are stored locally, so they can be cleared locally. The SESSION function is used to save the data on the server.
The following is the setting method: if we need to settext
Andsecond
. Assume thattext
The value is as follows: (jquery method)
Var text = $ ('# testinput'). val (); // This row is used to obtain the text value. You can use your own method.
document.cookie = "text=" + escape(text);
document.cookie = "second=2";
The above two rows are the method for setting the cookie value. First, in the cookie, the two sides are assigned values as above, and their names are different, which is equivalent to the following code:
document.cookie = "text="+escape(text)+"; second=2";
If the attribute name is different, it will not be overwritten.escape()
The function is used to escape, because the cookie name is generally not allowed./ = "
These symbols are names and values, but what if there are these symbols or spaces? Escape () is required for escape, so spaces are converted%20
This symbol,text1 text2
It will becometext1%20text2
This way.
Get cookie value
Obtaining cookies is as convenient as setting. The Code is as follows:
Var strCookie = document. cookie; // obtain all the cookie values of the current domain name var arrCookie = strCookie. split (";"); // use split to split the string. Remember that there is a space after the semicolon for (var I = 0; I <arrCookie. length; I ++) {var arr = arrCookie [I]. split ("="); // you can use = to separate the separated array content. If (arr [0] = "text") {// if the first half of the split is the same as the attribute name we need, alert (arr [1]); // The second half we get is the value of this attribute }}
In this way, you can easily obtain the cookie value.
However, when setting a cookie, you also need to set a cookie expiration time, which will be updated later.