js cookie
cookie : 客户端存储会话信息。
js中的cookie:
document.cookie = "name=value; expires=evalue; path=pvalue; domain=dvalue; secure=svalue;";
参数解析:
1. name = value : 表示要存入对象的名称,唯一且必须设置的参数(通常使用:user@domain格式命名,user为本地用户,domain为所访问网站的域名) = 要存储的值;
2. expires :该对象的有效事件(可选),默认浏览器会话结束失效;
3. path : 指定该Cookie的作用范围(可选);
4. domain:设置web服务器的Cookie共享域(可选);
5. secure:设置Cookie的传输过程是否加密(可选),一般为SSH加密;
当然,我们在实际使用中,一般只需要设置 name 及 expires 即可。
下面,参考js高级程序设计中关于cookie的封装,三个功能,获取,设置及删除(略有改动,请查看js高级程序设计第631页源码);
var CookieUtil = { get: function (name) { var cookieName = encodeURIComponent(name) + "=", cookieStart = document.cookie.indexOf(cookieName), cookieValue = null; if (cookieStart > -1) { var cookieEnd = document.cookie.indexOf(";", cookieStart); if (cookieEnd == -1) { cookieEnd = document.cookie.length; } cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd)); } return cookieValue; }, set: function (name, value, expires, path, domain, secure) { var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value); if (expires instanceof Date) { cookieText += "; expires=" + expires.toGMTString(); } if (path) { cookieText += "; path=" + path; } if (domain) { cookieText += "; domain=" + domain; } if (secure) { cookieText += "; secure"; } document.cookie = cookieText; }, remove: function (name) { this.set(name, "", -10); } }
根据以上代码,做的一个小示例,供大家参考:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" id="form1"> 用户名:<input type="text" name="username" id="username"/> <br/><br/> 密 码:<input type="text" name="userpass" id="userpass"/> <br/><br/> <input type="checkbox" name="cb1" id="cb1"/> 记住账号 <input type="checkbox" name="cb2" id="cb2"/> 记住密码 <br/><br/> <input type="submit" value="提交"/> </form> <script src="cookie.js"></script> <script !src=""> window.onload = function () { //获取元素 var oForm = document.getElementById("form1"); var oUserName = document.getElementById("username"); var oUserPass = document.getElementById("userpass"); var oCB1 = document.getElementById("cb1"); var oCB2 = document.getElementById("cb2"); var date = new Date(); date.setDate(date.getDate() + 1); oForm.onsubmit = function () { if (oCB1.checked) { CookieUtil.set("username", oUserName.value, date); } else { CookieUtil.remove("username"); } if (oCB2.checked) { CookieUtil.set("userpass", oUserPass.value, date); } else { CookieUtil.remove("userpass"); } } if (CookieUtil.get("username")) { oUserName.value = CookieUtil.get("username"); oCB1.checked = true; } if (CookieUtil.get("userpass")) { oUserPass.value = CookieUtil.get("userpass"); oCB2.checked = true; } } </script> </body> </html>
效果图如下: