DIV CSS 佈局教程網

用jquery.cookie.js實作「記住密碼」功能
編輯:JQuery特效代碼     

「記住密碼」是登入表單的標配,用 jQuery 搭配 cookie 插件就能幾行搞定。整體邏輯分兩半:頁面載入時檢查 cookie 決定要不要回填,使用者送出表單時再依勾選狀態決定寫入或清除。

//初始化頁面時驗證是否記住了密碼
$(document).ready(function() {
if ($.cookie("rmbUser") == "true") {
$("#rmbUser").attr("checked", true);
$("#user").val($.cookie("userName"));
$("#pass").val($.cookie("passWord"));
}
});
//保存用戶信息
function saveUserInfo() {
if ($("#rmbUser").attr("checked") == true) {
var userName = $("#user").val();
var passWord = $("#pass").val();
$.cookie("rmbUser", "true", { expires: 7 }); // 存儲一個帶7天期限的 cookie
$.cookie("userName", userName, { expires: 7 }); // 存儲一個帶7天期限的 cookie
$.cookie("passWord", passWord, { expires: 7 }); // 存儲一個帶7天期限的 cookie
}
else {
$.cookie("rmbUser", "false", { expires: -1 });
$.cookie("userName", '', { expires: -1 });
$.cookie("passWord", '', { expires: -1 });
}
}

幾個最核心的語法

$.cookie('the_cookie'); // 讀取 cookie
$.cookie('the_cookie', 'the_value'); // 存儲 cookie
$.cookie('the_cookie', 'the_value', { expires: 7 }); // 存儲一個帶7天期限的 cookie
$.cookie('the_cookie', '', { expires: -1 }); // 刪除 cookie

這裡有個實務上一定要留意的安全提醒:把密碼以純文字寫進 cookie,等於把鑰匙插在門上——任何能接觸到該瀏覽器的人都能直接讀出內容。正式環境請只記住使用者名稱,把憑證交給 token 或 session 管理;上面這段程式碼適合當作 cookie 操作的練習範例,上線前記得改掉。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved