最近項目用到登錄需求:
1.用戶正常登錄,即從登錄界面進入,如果從url進入提示:未登錄,請登錄。然后返回登錄界面。
2.用戶登錄后,10分鍾無操作,提示登錄超時,請重新登錄;
現在做個簡單演示,代碼如下:
login.html頁面中:html部分
<body>
<div class="header">
<p>SUMS軟件升級管理系統</p>
</div>
<div class="footer">
<div id="loginform" class="loginBox">
<form class="form" autocomplete="off">
<input name="username" type="text" placeholder="請輸入用戶名" class="username fl" id="username">
<input name="password" type="password" placeholder="請輸入密碼" class="password fl" id="password">
<div class="Hui-iconfont prompt-3" id="prompt-3"></div>
<div class="row clearfix forminput">
<input name="user" type="button" value="" class="user fl" id="user" > //登錄按鈕
<input name="power" type="button" value="" class="power fl" id="powerenter"> //登錄按鈕
</div>
</form>
</div>
</div>
</body>
login.html頁面中:script部分
<script type="text/javascript" src="lib/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function () {
// 登錄接口 這是登錄界面login.html的js代碼
$("#user").click(function () {
if(username.val().length == 0 || password.val().length == 0){ //簡單判斷用戶名和密碼不為空
return false;
}else{
var name = username.val();
var userurl = "index.html?usrname="+ name; //登錄到url連接並帶值
$.ajax({
type: "POST", //post方式
url: "/api/login",//登錄接口
data: {
username: username.val(),
password: password.val()
},
dataType: "json",
success: function (result) {
if (result.code == 0) { //后台返回狀態碼,code=0的時候登錄成功
var customerId = result.data.id; //將數據中用戶信息的ID賦值給變量
sessionStorage.customerId = customerId; //將變量存儲到本地sessionStorage中,並且value為customerID
window.location.href = userurl ; //跳轉連接 index.html頁面
} else {
$("#prompt-3").css("display","block").html(""+result.msg);//沒登錄時提示信息,后台做的判斷
}
},
error : function() {
alert("error!!");
}
})
}
});
})
</script>
index.html頁面根據customerId做功能判斷,判斷是否是正常登錄;
index.html頁面的script部分:
<script>
$(function () {
// 判斷是否登錄 未登錄返回登錄界面
var customerId= sessionStorage.customerId;//接收customerId的值
console.log(customerId);
if (customerId == undefined) { //判斷是否有值
alert("沒有登錄,請登錄");
window.location.href = "login.html";
}
//判斷長時間未操作就退出登錄
var lastTime = new Date().getTime();
var currentTime = new Date().getTime();
var timeOut = 10 * 60 * 1000; //設置超時時間: 10分鍾
$(function(){
/* 監聽鼠標移動事件 */
$(document).mouseover(function(){
lastTime = new Date().getTime(); //更新操作時間
});
});
function testTime(){
currentTime = new Date().getTime(); //更新當前時間
if(currentTime - lastTime > timeOut){ //判斷是否超時
alert("登錄超時,請重新登錄");
window.location.href = "login.html";
}
}
/* 定時器 間隔5秒檢測是否長時間未操作頁面 */
window.setInterval(testTime, 5000);
// 通過url將用戶名稱帶過來,用此方法漢字會亂碼
var indexurl = window.location.href.split("?")[1];
var temp = indexurl.split("&");
var tempname = temp[0].split("=")[1];
$(".currentname").text(tempname);
})
</script>
個人觀點,僅供參考!