JavaScript 使用Document記錄cookie,documentcookie

來源:互聯網
上載者:User

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表單提交的代碼   });


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.