JavaScript 使用Document記錄cookie,documentcookie
cookie對於我們使用者來說,有時協助還是挺大的,比如對於一些不是特別重要的網站,比如公司的測試平台,每次登陸都要手動輸入使用者名稱和密碼
很繁瑣。所以為了更少的引入其它架構,就直接使用js在登陸的頁面中寫一個記錄使用者名稱和密碼的代碼。而且不用在前台顯示是否記住密碼
直接在首次登陸後直接把使用者名稱和密碼記住即可。
<script language="javascript">function login() { //TODO一些表單提交判斷的代碼 remberPwd();}
function remberPwd() { var date=new Date(); var expiresDays=10; //將date設定為10天以後的時間 date.setTime(date.getTime()+expiresDays*24*3600*1000); //將userName和password兩個cookie設定為10天后到期 document.cookie="userName=admin; expires="+date.toGMTString(); document.cookie="password=12345; expires="+date.toGMTString(); }
根據Cookie的key擷取Value類似於Java中的Map
function getCookie(name) {var cookieValue = null;//返回cookie的value值
//cookie 是一個字串使用分號隔開
var cookieArray = document.cookie;//擷取cookie字串if (cookieArray!=null && cookieArray != '') {var cookies = cookieArray.split(';');//將獲得的所有cookie切割成數組 for ( var i = 0; i < cookies.length; i++) {var cookie = cookies[i];//得到某下標的cookies數組 var nt = cookie.substring(0, name.length+1);if (nt.indexOf(name)!=-1) {//如果存在該cookie的話就將cookie的值拿出來 cookieValue = cookie.substring(name.length+2,cookie.length);break}}}return cookieValue;}
//由於平台有jquery所以就直接使用了 $(function(){ <span style="white-space:pre"></span>var name = getCookie("userName");<span style="white-space:pre"></span>if(name == null) return;<span style="white-space:pre"></span>var pwd = getCookie("password");<span style="white-space:pre"></span>if(pwd == null) return;<span style="white-space:pre"></span>//TODO表單提交的代碼 });