1. 程式人生 > >原生JavaScript將賬號密碼儲存到cookie中

原生JavaScript將賬號密碼儲存到cookie中

這個是個很常見的小知識,寫個部落格來記錄一下,方便以後可以檢視和吃老本。

核心程式碼

var CookieHandle = {
        getCookie: function (cookieName) {
            if (document.cookie.length > 0) {
                var c_start = document.cookie.indexOf(cookieName + "=");
                if (c_start !== -1) {
                    c_start = c_start + cookieName.length + 1;
                    var c_end = document.cookie.indexOf(";", c_start);
                    if (c_end === -1) c_end = document.cookie.length;
                    return decodeURIComponent(document.cookie.substring(c_start, c_end));
                }
            }
            return "";
        },
        setCookie: function (cookieName, value, expiredays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + expiredays);
            var expire_cookie = cookieName + "=" + decodeURI(value) + ";expires=" + exdate.toUTCString();
            document.cookie = expire_cookie;
        }
    };

一般用於登入頁面,當用戶賬號密碼輸入正確的時候,儲存資訊到cookie中

	 CookieHandle.setCookie('username',accountNum,90);
         CookieHandle.setCookie('password',passwordNum,90);

當訪問登入頁 的時候,讀取cookie儲存的值並寫到輸入框中

var got_cookie_account = CookieHandle.getCookie('username');
	var got_cookie_password = CookieHandle.getCookie('password');
	$('#account').val(got_cookie_account);
	$('#password').val(got_cookie_password);