javascript 设置cookie和取得cookie
代吗实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>cookie</title> <script> function setCookie(name,value,expires,path,domain,secure) { var cookieName=encodeURIComponent(name)+'='+encodeURIComponent(value); if(expires instanceof Date ) { cookieName+=';expires='+expires; } if(path) { cookieName+=';path='+path; } if(domain) {domain cookieName+=';domain='+domain; } if(secure) { cookieName+=';secure'; } document.cookie=cookieName; } function getCookie(name) { var cookieName=encodeURIComponent(name)+'='; var cookieStart = document.cookie.indexOf(cookieName); if (cookieStart>-1) { var cookieEnd=document.cookie.indexOf(';',cookieStart); if(cookieEnd==-1){ cookieEnd=documet.cookie.length; } cookieValue=decodeURIComponent(document.cookie.substring(cookieStart+cookieName.length,cookieEnd)); return cookieValue; } } alert(getCookie('user')); alert(getCookie('email')); alert(getCookie('url')); function setCookieDate(day) { //传递一个天数,比如传递7,就7天后失效 var date = null; if (typeof day == 'number' && day > 0) { date = new Date(); date.setDate(date.getDate() + day); } else { throw new Error('您传递的天数不合法!必须是数字且大于0'); } return date; } </script> </head> <p>设置cookie和取得cookie </p> </body> </html>
效果:
设置cookie
火狐设置下隐私选项我们可以看到cookie,在localhost中我们可以看到结果。
cookie 中的user
cookie 中的url
cookie 中的email
取得cookie
16:45:06 2017-09-04
越努力越幸运