javascript - js设置cookie过期时间设置无效?
黄舟
黄舟 2017-04-11 11:49:44
0
2
862

我用js设置cookie的时候expires总是设置不成功

window.onload = function(){ var exp = new Date(); exp.setTime(exp.getTime() + 30 * 24 * 60 * 60 * 1000); exp = exp.toGMTString(); function setCookie(key, value, expires){ var cookieStr = key + "=" + value; if(expires){ cookieStr += "; " + "max-age" + "=" + 1000; } // cookieStr += "; domain=baidu.com; path=/"; document.cookie = cookieStr; console.log(document.cookie); } function getCookie(key){ var cookieName = key + "="; var startIndex = document.cookie.indexOf(cookieName); var value = null; if(startIndex != -1){ var endIndex = document.cookie.indexOf(";", startIndex); if(endIndex == -1){ endIndex = document.cookie.length; } value = document.cookie.substring(startIndex + cookieName.length, endIndex); } return value; } if(!getCookie("name")){ document.getElementById("result").innerHTML = "Welcome!"; setCookie("name", "xiaota", exp); } else{ document.getElementById("result").innerHTML = "Welcome " + getCookie("name") + "!"; }

调用setCookie函数的时候,传入时间,console.log打印的结果并没有expires,不知道怎么回事。

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all (2)
左手右手慢动作

其实过期时间已经设好了,但是max-ageexpires是不可见的。document.cookie里只能看到cookie的key:value

目前大多数浏览器都可以查看cookie的max-ageexpires

以Chrome为例:在devTool - Application - Storage - Cookies里面可以看到cookie的所有属性。

    大家讲道理

    function setCookie(name,value,days){//设置cookie

    var d = new Date(); d.setTime(d.getTime() + (days*24*60*60*1000)); var expires = "expires="+d.toUTCString(); document.cookie = name + "=" + value + "; " + expires;

    }

      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!