本文介绍利用sessionStorage存储customerID来判断用户登录状态,进而控制页面跳转逻辑。通过封装jumpTo函数处理未登录时的重定向,并结合jQuery监听Enter键触发登录接口,实现完整的登录跳转流程。
JavaScript判断登录状态并实现页面跳转
本文介绍一种利用JavaScript判断用户登录状态并决定页面跳转路径的方法,供开发者参考。
核心思路是利用sessionStorage存储用户标识(如customerID),以此判断登录状态,并据此决定页面应跳转至何处。
基于sessionStorage的跳转逻辑
具体实现需判断本地是否存在customerID:
function jumpTo(p, url) {
var customerId=sessionStorage.customerId;
if (customerId == undefined) {
p.attr("href", "page/Login/login.html");
<span style="white-space:pre"> </span>} else {
p.attr("href", url);
}
}
function infoJumpTo() {
var $info = $("#info");
jumpTo($info, "http://localhost/page/AmountAscension/amountAscension.html");
}
function starJumpTo() {
var $star = $("#star");
jumpTo($star, "http://localhost/page/MyAccount/myAccount.html");
}
在HTML中,为相应的a标签添加onclick事件,例如调用infoJumpTo函数即可实现跳转逻辑。
登录状态存储与Enter键处理
那么,登录页面的customerID是如何被存储到本地session中的呢?
function confirm(){
var tel=$tel.val();//获取页面中登录名和密码
var pwd=$pwd.val();
if(tel==""|| pwd==""){//判断两个均不为空(其他判断规则在其输入时已经判断)
alert("手机号密码均不能为空!")
return false;
}else{//以上均符合要求,则调用登录esb接口
$.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;//将数据中用户信息的ID赋值给变量
sessionStorage.customerId = customerId;//将变量存储到本地sessionStorage中,并且value为customerID
window.location.href='http://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键提交,而非手动点击登录按钮。此时可借助以下JavaScript代码处理:
//判断是否敲击了Enter键
$(document).keyup(function(event){
if(event.keyCode ==13){
$("#login").trigger("click");
}
});
希望上述内容对您的JavaScript程序设计有所助益。