js中cookie設置、獲取與清除


// 設置cookie
    setCookie (cname, cpwd, exdays) {
      var exdate = new Date()// 獲取時間
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays)// 保存的天數
      // 字符串拼接cookie  
//默認情況下,cookie 在瀏覽器關閉時刪除, 使用 path 參數告訴瀏覽器 cookie 的路徑。默認情況下,cookie 屬於當前頁面(path=/)。
//cookie 設置過期時間 (expires=)
window.document.cookie = 'userName' + '=' + cname + ';path=/;expires=' + exdate.toGMTString() window.document.cookie = 'userPwd' + '=' + cpwd + ';path=/;expires=' + exdate.toGMTString() }, // 讀取cookie getCookie: function () { if (document.cookie.length > 0) { var arr = document.cookie.split('; ')// 這里顯示的格式需要切割一下自己可輸出看下 for (var i = 0; i < arr.length; i++) { var arr2 = arr[i].split('=')// 再次切割 // 判斷查找相對應的值 if (arr2[0] === 'userName') { this.ruleForm.userName = arr2[1]// 保存到保存數據的地方 } else if (arr2[0] === 'userPwd') { this.ruleForm.password = arr2[1] } } } }, // 清除cookie clearCookie: function () { this.setCookie('', '', -1)// 修改2值都為空,天數為負1天就好了 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM