1. 程式人生 > >登入退出時設定cookie,獲取cookie,刪除cookie,捨棄jquery.cookie.js外掛

登入退出時設定cookie,獲取cookie,刪除cookie,捨棄jquery.cookie.js外掛

前言:公司以前用的jquery.cookie.js外掛來存取刪cookie,要求退出登入時,刪除cookie,在未正常退出登入時,下次登入可自動登入,but用該外掛的$.cookie("username",null,-1);並不管用,查了一些方法解決好像並不管用,可能本人外掛的版本或專案自身問題:

設定cookie

清快取

所以果斷捨棄,檢視官網 封裝了以下三個方法:解決cookie存取刪問題

//設定cookie
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires+"; path=/";//path=/是根路徑
}
//獲取cookie
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
    }
    return "";
}
//清除cookie
function clearCookie(name) {
    setCookie(name, "", -1);
}
 setCookie("remember", "true", {expires: 7}); //儲存一個帶7天期限的cookie
 setCookie("username", "userValue", {expires: 7});
 setCookie("password", "password", {expires: 7});
 getCookie("remember");//獲取對應cookie值
 getCookie("username");
 getCookie("password");
 clearCookie("remember");//刪除cookie值
 clearCookie("username");
 clearCookie("password");