How to operate cookies using pure JS

php中世界最好的语言
Release: 2018-03-07 16:41:21
Original
2229 people have browsed it

This time I will show you how to operate pure JS operations Cookie, what are the precautions for operating pure JS cookies , the following is a practical case, let's take a look.

A cookie is a variable that is stored on the visitor's computer. This cookie is sent each time the same computer requests a page through a browser. You can use JavaScript to create and retrieve cookie values.

Add Cookie

Description:

Create a new cookie and let it be managed by the browser!

Parameter description:

name - key The key of the value pair, uniquely marks a value

value - the value of the key-value pair, the content stored in the cookie

expdays - cookie expiration time (valid time)

function setCookie ( name, value, expdays ){    var expdate = new Date();    //设置Cookie过期日期
    expdate.setDate(expdate.getDate() + expdays) ;    //添加Cookie
    document.cookie = name + "=" + escape(value) + ";expires=" + expdate.toUTCString();
}
Copy after login

Get Cookie

Description:

According to the parameter name, get the corresponding value in the cookie

function getCookie ( name ){    //获取name在Cookie中起止位置
    var start = document.cookie.indexOf(name+"=") ;    if ( start != -1 )
    {
        start = start + name.length + 1 ;        //获取value的终止位置
        var end = document.cookie.indexOf(";", start) ;        if ( end == -1 )
            end = document.cookie.length ;        //截获cookie的value值,并返回
        return unescape(document.cookie.substring(start,end)) ;
    }    return "" ;
}
Copy after login

Delete Cookie

Description:

According to name, delete a cookie (set to expire immediately)

function delCookie ( name ){
    setCookie ( name, "", -1 ) ;
}
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

What should I do if the browser is not compatible with the code I wrote

Summary of commonly used array methods in JS

Detailed graphic explanation of Vue.js

##How to use xml2js in nodej

Summary of using Pixi.js

The above is the detailed content of How to operate cookies using pure JS. For more information, please follow other related articles on the PHP Chinese website!

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!