Home > Web Front-end > JS Tutorial > Detailed explanation of cookie operations in JS

Detailed explanation of cookie operations in JS

黄舟
Release: 2017-03-01 14:35:56
Original
953 people have browsed it


Preface

Cookie settings


##Parameter description:

name Cookie name, key value
value Optional, cookie value
expire Optional, expiration time, timestamp format
path Optional, server-side valid path, / means the entire domain name is valid, the default is the path of the page when the cookie is currently set
domain Optional, the domain name that this cookie is valid for
secure Optional. Specifies whether cookies are transmitted over a secure HTTPS connection.

Code Encapsulation

(function(){
    var cookieObj={
            'add':function(name, value, hours){ //修改或是添加cookie
                var expire = "";
                if(hours != null){
                    expire = new Date((new Date()).getTime() + hours * 3600000);
                    expire = "; expires=" + expire.toGMTString();
                }               
                document.cookie = name + "=" + escape(value) + expire + ";path=/";
                //如果指定域名可以使用如下
                //document.cookie = name + "=" + escape(value) + expire + ";path=/;domain=findme.wang";
            },
            'get':function(c_name){//读取cookie
                if (document.cookie.length>0){
                      c_start=document.cookie.indexOf(c_name + "=")
                      if (c_start!=-1){ 
                        c_start=c_start + c_name.length+1 
                        c_end=document.cookie.indexOf(";",c_start)
                        if (c_end==-1){
                            c_end=document.cookie.length
                        }
                        return unescape(document.cookie.substring(c_start,c_end))
                        } 
                      }
                    return "";
            }
    };
    window.cookieObj=cookieObj;}());
Copy after login

Call Test

cookieObj.add('myWeb','http://www.findme.wang');
console.log('myWeb:'+cookieObj.get('website'));
Copy after login

Detailed explanation of cookie operations in JS

The above is a detailed explanation of the operation of Cookies in JS, and more related content Please pay attention to the PHP Chinese website (m.sbmmt.com)!



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