Cookie Learning Guide

Source: Internet
Author: User

First, what is a cookie

Cookies are also called HTTP cookies, which are originally used for client and server-side sessions, because HTTP is a stateless protocol, in order to maintain the user and to track user information, so the introduction of cookies and Session,cookie is primarily stored in the client, Session is stored on the server side of the

Ii. Limitations of cookies

The number of cookies under each specific domain name is limited, Fixfox is 50, opera is 30, Chrome and Safari are unlimited, and each cookie has a maximum limit of 4K, if the content of the cookie exceeds 4K, Then the call will return an empty string.

It is important to note that, if the cookie is stored on a local disk, then chrome cannot be output in the console, this time the solution is to try a different browser

PS: Since HTTP will be attached every time you initiate a network request, for functionality and performance considerations, you should minimize the number of cookies used and use a relatively small cookie

Third, the basic use of cookies

Cookies have the concept of domain and path . Domain is the concept of domains, because browsers are a security-aware environment, so there is no mutual access to cookies between different domains (of course, through special settings to achieve cookie cross-domain access). The path is the concept of routing, a Web page created by the cookie can only be used in the same directory or subdirectory of the page to access all the pages, and can not be accessed by other directory pages

a cookie is a storage method consisting of key-value pairs in the approximate format of Name=value
document.cookie=name=value;[ Exprises=date];      [Path=path] [] for optional content

Here we introduce a small example to introduce, cookie hypothesis we want to make such a function, in the user login interface when the user's personal information stored in a cookie for later use, the relevant code is as follows:

<HTML>    <Head>        <title>Analog User Login Demo</title>        <MetaCharSet= "Utf-8" >    </Head>    <Body>        <Table>            <TR>                <TD>                <inputID= "User"placeholder= "User name"type= "text"style= "width:200px;" />                </TD>            </TR>            <TR>                <TD>                <inputID= "pwd"placeholder= "Password"type= "Password"style= "width:200px;">                </TD>            </TR>            <TR>                <TD>                <inputonclick= "Btn_certain ()"ID= "certain"value= "OK"type= "button"style= "Background:blue;color:white" />                </TD>            </TR>        </Table>            </Body>    <Script>        functionBtn_certain () {//gets the object of the input control            varUser=document.getElementById ("User"); varpwd=document.getElementById ("pwd"); //get the value when clicked            varInput_user=User.value; varinput_pwd=Pwd.value; Console.log ('uername='+input_user); //write these two values into the cookie separatelyDocument.cookie="uername=123"; Document.cookie="userpwd="+input_pwd; }        //Btn.onclick (function () {            //alert (1);        //});            </Script></HTML>

Run the results as follows:

From here we can see that two local cookies have been generated for the two cookies, username and userpwd, and it is important to note that the local cookie cannot be viewed under Hcrome, so the above example is viewed under Fixfox

Not to have the careful classmate found that The above example creates two cookies by repeating doucment.cookie This property, but this is different from the concept of string overlay in JavaScript, every cookie is created to call Doucment.cookie, so that only the cookie will not overwrite the previous The cookie Content

The above example illustrates how to create a cookie, and it can also be used to modify a cookie, The same is true of the cookie principle. When you assign a string to Document.cookie, if it is a name that does not exist, a new cookie is created, and if the cookie is present, the value of the cookie corresponds to the change

Already said the implementation of the new and modified, and then left to delete and query cookies

And then we'll start with the removal step-by-step.

Delete Cookies

There is no way to delete cookies directly in the cookie operation, but we can think in a different direction because Cokie has a valid time, so if we let the cookie expire in time, then this cookie is equivalent to not being effective. So the effect can be the same as being deleted (the default cookie does not set the period of time is expired when you close the browser)

We add a button and a Y trigger script according to the example above, as follows:

functionBtn_deleteuser () {//gets the value of the user input box            varUser=document.getelementbyid ("User"); varinput=User.value; //Create a Time object and get the current time            varDate=NewDate (); //set the time to the day before the current timeDate.setdate (Date.getdate ()-1); //convert time into GMT format            varTime=date.togmtstring (); //set the expiration time for a fieldDocument.cookie= "Uername=" +input+ "expires=" +Time ; }

The idea of this script is to implement the ability to delete a cookie.

Find cookies

Here to find out whether the value of a cookie exists, here we specifically to do is to determine whether the value of the cookie is empty, and then to determine whether the cookie you entered is a name exists, if there is a value to obtain its corresponding values, the specific code W3 school has been given, Specific as follows:

functionGetCookie (c_name) {if(document.cookie.length>0) {//Check whether the cookie is empty and return ""C_start=document.cookie.indexof (c_name + "=")//checks whether the cookie exists by using the string object's indexof (), which does not exist-1        if(C_start!=-1) {C_start=c_start + c_name.length+1//the last +1 actually means "=", so we get to where the cookie value starts .C_end=document.cookie.indexof (";", C_start)//in fact, I just saw indexof () The second argument suddenly a little dizzy, and later remembered to indicate the location of the specified start index ... This sentence is to get the end position of the value. Because you need to consider whether it is the last item, so pass ";" Whether the number exists to Judge          if(c_end==-1) c_end=Document.cookie.lengthreturnUnescape (document.cookie.substring (c_start,c_end))//the value is obtained by substring (). Want to understand unescape () to know what escape () is to do, are very important basis, want to know can be searched, at the end of the article will also explain the cookie coding details}}return""}

Deletion of all Cookies

To achieve the deletion of all cookies, according to my implementation of the idea is that the string cut through the method of each string, such as: Name=value, and then the string after each cut after the small string to add an expiration time, so that the cookie can be completely deleted .

Iv. Other uses of cookies

In addition to the Exprise attribute, this property is used to set the path to the cookie, which is accessed by default on the subdirectory of the current cookie page. However, by default we cannot access this cookie under any other parent directory, and we can do this by setting a cookie.

We assume that our files are stored in www.leslieyong.com/cn/dowload/index.html, so we can access cookies by default under the Dowload directory. At this point, we can set the Path property to achieve the effect that can be accessed under the Www.leslieyong.com root directory, as follows:

Document.cookie = "name=value;expires=date;path=/"

To implement this can be accessed under the CN directory it should be written like this

Document.cookie = "name=value;expires=date;path=/cn/"

As said above, we can achieve in the same domain between the value of the transfer, but in the cross-domain of how to implement the value, in fact, in addition to the cookie path, there is domain,domain this attribute can be implemented across domains, but must ensure that the two domain names have a public part, what is the public part? is like www.qq.com and www.sport.qq.com this has the same qq.com domain name, the specific use method is to set domain as the same part of the domain name, as follows:

Document.cookie = "name=value;expires=date;path=/;d omain=qq.com"

In addition, when using cookies, we also need to pay attention to the problem of encoding the cookie, because the cookie does not support commas, spaces, semicolons, so when setting up a cookie, you need to use Escape () to transcode the input information, Then use Unescape () at the time of the call to re-convert back, this input JavaScript basic knowledge of the scope, unclear please Baidu

Cookie Learning Guide

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.