很多頁面的按鈕需要「登入才去、沒登入就先導向登入頁」。用 sessionStorage 存一個身分辨識碼,就能在前端完成這道判斷。
把跳轉邏輯抽成一個共用函式,依 session 裡有沒有 customerId 決定目標網址:
function jumpTo(p, url) {
var customerId = sessionStorage.customerId;
if (customerId == undefined) {
p.attr("href", "page/Login/login.html");
} else {
p.attr("href", url);
}
}
function infoJumpTo() {
var $info = $("#info");
jumpTo($info, "https://localhost/page/AmountAscension/amountAscension.html");
}
function starJumpTo() {
var $star = $("#star");
jumpTo($star, "https://localhost/page/MyAccount/myAccount.html");
}
HTML 裡對應的 a 標籤只要寫 onclick="infoJumpTo()" 就能接上。
按下登入鈕時,先檢查手機號與密碼是否都填了,再呼叫登入介面;成功後把回傳的使用者 ID 存進 sessionStorage,然後導向首頁。
function confirm(){
var tel = $tel.val(); //獲取頁面中登錄名和密碼
var pwd = $pwd.val();
if (tel == "" || pwd == "") {
alert("手機號密碼均不能為空!")
return false;
} else {
$.ajax({
url: config.baseServerUrl + '/account/login', //相對應的 esb 接口地址
type: 'post',
data: { mobile: tel, password: pwd },
success: function(data){
if (data.success) {
var customerId = data.attr.customerInfo.id;
sessionStorage.customerId = customerId; //存入本地 sessionStorage
window.location.href = 'https://localhost/index.html';
} else {
if (tel != data.tel) {
alert(data.message); $tel.val(""); $pwd.val(""); return false;
}
if (pwd != data.pwd) {
alert(data.message); $pwd.val(""); return false;
}
}
}
})
}
}
多數使用者習慣打完資料直接按 Enter,而不是去點登入鈕,所以補一段鍵盤監聽:
//判斷是否敲擊了Enter鍵
$(document).keyup(function(event){
if (event.keyCode == 13) {
$("#login").trigger("click");
}
});
這裡有個安全提醒值得記住:sessionStorage 只是前端的便利性判斷,使用者完全可以自行清空或竄改,因此它只能拿來決定「要不要先帶去登入頁」,真正的權限驗證一定要放在伺服器端每一則需要保護的請求上。
希望本文所述對大家的 JavaScript 程序設計有所幫助。