0
点赞
收藏
分享

微信扫一扫

cookie与localstorage

流沙雨帘 2022-02-07 阅读 72

因为http是一个无状态的协议,

cookie

cookie原理

1,首先浏览器第一次发送请求给服务器,服务器收到后,在响应头中进行设置,set-cookie,然后返回给浏览器。

2,浏览器收到响应的信息,把响应请求中的cookie保存起来。

3,于是当浏览器进行第二次请求的时候,就会携带cookie。

4,服务器收到请求后验证cookie,验证成功后,就会返回相应的内容。

注意:

1,set-cookie由服务器设置,前端无法设置

2,http协议规定的,每次http请求都会携带cookie,但是有些数据在这次请求中并不需要,但是http协议,任然会携带,所以要慎重使用。一般用于登录的验证。

3,cookie不可跨域,在百度只能存百度的cookie,淘宝只能存淘宝的cookie。但是在一级域名与二级域名,可以通过设置Domain互相进行访问。

4,cookie存储在浏览器中

5,cookie的存储有大小的限制 不同浏览器各不相同 数量在50个左右,大小在4kb左右

6,cookie存储的时间很灵活

7,cookie在前端与后端都可以设置

cookie使用

key:value

document.cookie='name=sdy';    //document.cookie每次只能设置一个cookie的属性

document.cookie='color=black; domain=127.0.0.1; path=/doc';

 cookie的属性

        name        cookie的名字,具有唯一性

        value        cookie的值,都是字符串

        domain        设置cookie在哪个域名下,是有效的

        path        cookie的所在的路径

        express        cookie的过期时间

        max-age        cookie的有限时间    

        HttpOnly        有这个标记的cookie,前端无法获取

        Secure        设置cookie只能通过HTTPS传输

        SameSite        设置cookie在跨域请求的时候,不能被发送   

  封装cookie的属性

                let manageCookie = {
            //设置cookie    
            set: function (name, value, date) {
                //expires   传入的是时间节点
                //date过期的时间默认单位为天
                // var endDate = new Date();
                // endDate.setDate(endDate.getDate() + date);
                // document.cookie = `${name}=${value};expires=${endDate};`;

                //要求用户传入的date为秒数
                document.cookie = `${name}=${value};max-age=${date};`;
            },
            //移除cookie
            remove: function (name) {
                //直接将cookie的max-age设为0
                this.set(name, '', 0);

            },
            //获取cookie
            get: function (name) {
                let result = document.cookie.split(';');
                for (let i = 0; i < result.length; i++) {
                    let arr = result[i].split('=');
                    if (name == arr[0].trim()) {
                        return arr[1];
                    }
                }
            }
        }

练习

           //封装cookie属性
        let manageCookie = {
            //设置cookie    
            set: function (name, value, date) {
                //expires   传入的是时间节点
                //date过期的时间默认单位为天
                // var endDate = new Date();
                // endDate.setDate(endDate.getDate() + date);
                // document.cookie = `${name}=${value};expires=${endDate};`;

                //要求用户传入的date为秒数
                document.cookie = `${name}=${value};max-age=${date};`;
            },
            //移除cookie
            remove: function (name) {
                //直接将cookie的max-age设为0
                this.set(name, '', 0);

            },
            //获取cookie
            get: function (name) {
                let result = document.cookie.split(';');
                for (let i = 0; i < result.length; i++) {
                    let arr = result[i].split('=');
                    if (name == arr[0].trim()) {
                        return arr[1];
                    }
                }
            }
        }
        //实现拖拽功能,利用cookie存储数据
        let drag = {
            //初始化
            init: function (dom) {
                this.dom = dom;
                if (manageCookie.get('left')) {
                    this.dom.style.marginLeft = manageCookie.get('left') + 'px';
                } else {
                    this.dom.style.marginLeft = 0;
                };
                if (manageCookie.get('top')) {
                    this.dom.style.marginTop = 0;
                }
                this.bindEvent();
            },
            bindEvent() {
                this.dom.onmousedown = this.mouseDown.bind(this);
            },
            mouseDown: function (e) {
                //首先获得得是鼠标在物体内部得距离
                this.clickLeft = e.clientX - this.dom.offsetLeft;
                this.clickTop = e.clientY - this.dom.offsetTop;
                //鼠标移动时的方法
                document.onmousemove = this.mouseMove.bind(this);
                //鼠标抬起时的方法
                document.onmouseup = this.mouseUp.bind(this);

            },
            //移动时的方法
            mouseMove: function (e, left, top) {
                this.newLeft = e.clientX - this.clickLeft;
                this.newTop = e.clientY - this.clickTop;
                this.dom.style.marginLeft = this.newLeft + 'px';
                this.dom.style.marginTop = this.newTop + 'px';
            },
            //鼠标抬起时的方法
            mouseUp: function (e) {
                //结束移动与抬起得事件
                document.onmousemove = null;
                document.onmouseup = null;
                //存储在cookie中
                manageCookie.set('left', this.newLeft);
                manageCookie.set('top', this.newTop);
            }

        }
        drag.init(document.getElementsByClassName('drag')[0]);

webstorage        

大小在5mb左右        与http协议没有任何关系

localstorage         无时间限制

sessionstorage        (属于会话性得存储,仅在当前窗口有效)有时间限制

属性与方法

length

key()        通过索引查找数据

getItem(name)        通过键名取到数据

setItem(name,value)       设置一个本地存储的数据

//存储对象的方式
var color = {name:'red',num:100};
localStorage.setItem('color',JSON.stringify(color));

remove(name)         删除一个数据

clear()                清空本地存储数据

storage        事件        在第一个页面使用的storage,然后在第二个页面修改后,会在第一个页面触发        但是在第一个页面修改却不会发生

window.addEventListener('storage',function (ev) {
    console.log('在第一个页面修改购物车,会在第二个页面打印,在第二个页面修改后,会在第一个页面打印');
    ev.key    //表示修改的哪一个localstorage的属性
    ev.newValue    //修改后的数据
    ev.oldValue    //修改前的数据
    ev.storageArea    //storage的对象
    ev.url    //返回操作页面的url
})
举报

相关推荐

0 条评论