H5之旅

Cookie的重新认识

2017-03-20  本文已影响3人  聆听者JYZ

基本认识:

1、cookie是页面用来保存一些信息的,比如用户名 密码等(自动登录等)

2、注意:cookie和网页缓存没有任何关系,网页缓存缓存的额是页面

3、特性:

(1)他是完全存在客户端上的,是不安全的(也没有加密什么的,只是转了次码)

(2)同一个网站共享的是一个cookie

(3)数量 大小是有限的(一般不超过50个)

(4)过期时间(不指定过期时间,在浏览器关闭时失效)

(5)在cookie中=以为这添加,不会覆盖前面赋的值

4、注意,我们存cookie时,有时会默认在key前面加个空格,这可能导致我们去取时,取不到值,所以在封装回去cookie的值时,一定要注意注意下空格

代码示例:

<head>
    <meta charset="UTF-8">
    <title>cookie实践</title>
</head>

<script>
//    var odate = new Date();
//    //设置当前时间+30天
//    odate.setDate(odate.getDate()+30);
//    alert(odate.getFullYear()+"-"+(odate.getMonth()+1)+"-"+odate.getDate())
    //添加cookie并设置过期时间为当前时间向后30天
    //document.cookie="userName=jiayazi; expires="+odate;
    //设置cookie封装方法
    function setCookie(name,value,expires) {
        var newDate = new Date();
        newDate.setDate(newDate.getDate()+expires);
        document.cookie=name+'='+value+';expires='+expires;
    }
    //取出cookie的值
    function getCookie(cookieName) {
        var cookieList = document.cookie.split(';');
        for(var i=0; i<cookieList.length; i++){
            var oneCookieArr = cookieList[i].split('=');

            var oneCookieName = oneCookieArr[0];
            while (oneCookieName.charAt(0)==' ') { //判断一下字符串有没有前导空格
                oneCookieName = oneCookieName.substring(1,oneCookieName.length); //有的话,从第二位开始取
            }

            if(oneCookieName==cookieName){
                return oneCookieArr[1];
            }
        }
        return '';
    }
    //删除cookie
    function removeCookie(removeCookieName) {
        setCookie(removeCookieName,' ',-1);
    }


    //页面刚加载时会自定执行该方法
    window.onload=function () {

        alert(document.cookie);
        var form1 = document.getElementById('login');
        var userName = document.getElementById('username');

        form1.onsubmit=function () {
            setCookie('userName',userName.value,30);
        }

        userName.value=getCookie('userName');

        var cleanBtn = document.getElementsByTagName('a')[0];
        cleanBtn.onclick=function () {

            removeCookie('userName');
            userName.value='';
        }
    }

</script>

<body>

    <form id="login" action="http://www.baidu.com/">

        用户名:<input type="text" id="username"/><br/>
        密 码:<input type="password" id="password"/><br/>
        <input type="submit" value="提交">
        <a href="javascript:;" style="font-size: 12px"> 忘记密码 </a>

    </form>

</body>
上一篇 下一篇

猜你喜欢

热点阅读