Home > Web Front-end > JS Tutorial > body text

Cookies are used in JavaScript

高洛峰
Release: 2016-11-19 16:19:30
Original
931 people have browsed it

Cookie is a piece of data sent by the server to the browser after the browser accesses the server. Cookies are part of the http protocol. When the client sends a request to the server for the first time, the server will send a cookie to the client to save some information. When the client sends a request to the same server next time , the server takes corresponding actions by identifying the client's cookie. For example, when we log in to a website, the website records our username and password, so we can log in directly without having to enter our username and password the next time we log in.

The Web server creates a cookie by sending a Set-Cookie HTTP message header. The Set-Cookie message header is a string with the following format:

Set-Cookie: NAME=VALUE;Expires=DATE;Path=PATH;Domain=DOMAIN_NAME;SECURE
Copy after login

NAME: The name of the cookie, value is the value of the set cookie.

Expires: Determine the cookie expiration date, specify when the cookie will no longer be sent to the server, and the browser will delete the cookie after this specified time. The DATE attribute value must be in a specific format: Wdy (day of the week), Date-Month-Year HH:MM:SS GMT. If it is not in this format, it will not be recognized. When the expires option is not set, the cookie's life cycle is limited to the current session, and the cookie file will disappear automatically when the browser is closed.

Path: Controls the timing of sending the Cookie header. The web server will only send the Cookie header when the path specified by Path exists in the resource URL requested by the user. Generally, if the path part of the URL entered by the user contains the string defined by the Path attribute starting from the first character, the browser will consider it to have passed the check. If the value of the Path attribute is "/", all WWW resources on the Web server can read the cookie. If the path option is not set, the Path attribute value defaults to the path name of the resource passed to the browser by the web server.

Domain: Determine which web servers in the Internet domain can read the cookies accessed by the browser, that is, only pages from this domain can use the information in the cookies. When the Domain option is not set, the cookie attribute value is set to the domain name of the web server.

需要注意的是,只有在 domain 选项核实完毕之后才会对 path 属性进行比较。
Copy after login

SECURE: Only flag with no value, a cookie containing the secure option can be sent to the server only when a request is made over SSL or HTTPS. Indicates that only when the communication protocol between the browser and the Web server is an encryption authentication protocol, the browser will submit the corresponding cookie to the server.

In JavaScript, cookies are used to save state and provide an identification mechanism for web browsers. In JavaScript we can create, maintain and delete cookies through the document.cookie property.

Set cookies:

document.cookie="userName = mavis ";
Copy after login

Each cookie is a name/value pair. If you want to set multiple name/value pairs at one time, you can use the following method:

document.cookie = "userName=mavis; userId = 023";
Copy after login

In the cookie, use the escape() function to encode , it can use hexadecimal representation of some special symbols, such as semicolon (;), comma (,), equal sign (=), space, etc. However, after using escape() encoding, you need to use unescape() to decode after taking out the value to get the original cookie value.

The escape() function in JavaScript can encode a string so that the string can be read on all computers. The syntax is as follows: escape(string), string is the string to be escaped or encoded.

Get the value of cookie:
Use document.cookie to directly obtain a string consisting of multiple name/value separated by semicolons. These name/value pairs include all cookies under this domain name.

var myCookie = document.cookie;
Copy after login

Get the specified cookie value,

    //设置两个cookie
    document.cookie = "userName=mavis";
    document.cookie = "userId = 023";
    //获取cookie字符串
    var myCookie = document.cookie;
    var arrCookie = myCookie.split(";");
    var userName;
    for(var i = 0;i < arrCookie.length;i++){
    var myArr = arrCookie[i].split("=");
    //找到名称为userName的cookie,并返回值
    if(userName = myArr[0]){
        userName = myArr[1];
        break;
        }
    }
    alert("welcome " + userName);
Copy after login

Set the cookie expiration date:
When we log in to a website for the first time with our ID, some websites will prompt whether to save the ID and password in JavaScript , actually sets an expiration date for the cookie:

document.cookie = "userId = 023; expiress = GMT_String";
Copy after login

This statement sets the userId cookie to the expiration time represented by GMT_String. If this time is exceeded, the cookie will disappear and can no longer be accessed. Set the cookie value to expire after 30 days:

    //获取当前时间 
    var date=new Date(); 
    var expiresDays=30; 
    //将date设置为30天以后的时间 
    date.setTime(date.getTime()+expiresDays*24*3600*1000); 
    //将userId和userName两个cookie设置为30天后过期 
    document.cookie = "userId = 023; userName = mavis; expires = " + date.toGMTString();
Copy after login

This way you can delete the userId cookie.

Specify the path of accessible cookies: Specify by setting the path attribute

//指定可访问该cookie的目录
document.cookie = "name = mavis; path = cookiePath"

//在整个网站都可访问
    document.cookie = "name = mavis; path = /"
Copy after login

Specify the host name of accessible cookies: Host names refer to different hosts under the same domain. Cookies created in one host are under another host. It cannot be accessed, but it can be controlled through the domain parameter.
For example: document.cookie="name=value;domain=.baidu.com"; This setting allows all hosts under Baidu to access the cookie.

An example:

function getCookie(name){
        if (document.cookie.length>0){
            start=document.cookie.indexOf(name + "=")
            if (start!=-1){ 
                start=start + name.length+1 
                end=document.cookie.indexOf(";",start)
                if (end==-1) end=document.cookie.length
                    return unescape(document.cookie.substring(start,end))
            } 
        }
        return ""
    }

    function setCookie(name,value,expiredays){
        var exdate=new Date()
        exdate.setDate(exdate.getDate()+expiredays)
        document.cookie=name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    }
   setCookie("username","tank",1800); //设置cookie的值,生存时间半个小时
   alert(getCookie('test')); //取得cookie的值,显示tank
Copy after login

But there was a problem when running, and it could not be displayed on my chrome browser:

Cookies are used in JavaScript

So I checked online for the following reasons, because the chrome browser has restrictions on cookies. , but the cookie I gave to the Chrome browser has been set to "Allow local data to be set", but it still doesn't work. For those of you who read this article, can anyone tell me why this is? Grateful.

It is displayed like this on the edge browser:

Cookies are used in JavaScript

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!