javascript设置和获取cookie的通用方法

//设置cookie function setCookie(cookieName,cookieValue,cookieExpires,cookiePath) { cookieValue = escape(cookieValue);//编码latin-1 if(cookieExpires=="") { var nowDate = new Date(); nowDate.setMonth(nowDate.getMonth()+6); cookieExpires = nowDate.toGMTString(); } if(cookiePath!="") { cookiePath = ";Path="+cookiePath; } document.cookie= cookieName+"="+cookieValue+";expires="+cookieExpires+cookiePath; }  

//获取cookie function getCookieValue(cookieName) { var cookieValue = document.cookie; var cookieStartAt = cookieValue.indexOf(""+cookieName+"="); if(cookieStartAt==-1) { cookieStartAt = cookieValue.indexOf(cookieName+"="); } if(cookieStartAt==-1) { cookieValue = null; } else { cookieStartAt = cookieValue.indexOf("=",cookieStartAt)+1; cookieEndAt = cookieValue.indexOf(";",cookieStartAt); if(cookieEndAt==-1) { cookieEndAt = cookieValue.length; } cookieValue = unescape(cookieValue.substring(cookieStartAt,cookieEndAt));//解码latin-1 } return cookieValue; } 

 

一个小例子:

cookie

用户名:
密  码: 记住用户名
 

 

注意:

由于google Chrome浏览器为了安全只支持online-cookie,所以在本地测试时是没有效果的,需要上传到服务器试一下。

你可能感兴趣的:(JavaScript)