localStorage中的userData
项映射到从服务器传递的JSON字符串。
我想要做的是每次PHP会话结束时从localStorage中删除此项,并将userId设置为默认值。
variables.js
var userIdDefault = 1;
var sessionDuration = 1440;
if(localStorage.getItem('userData')) {
var userDataStored = JSON.parse(localStorage.getItem('userData'));
var userId = userDataStored["userId"];
var sessionStartTime = parseInt(userDataStored["sessionStartTime"]);
var sessionStopTime = sessionStartTime + sessionDuration;
}
else {
var userId = userIdDefault;
}
main.js
$(document).ready(function() {
if(userDataStored) {
var timeNow = Math.floor(new Date().getTime() / 1000);
waitTime = sessionStopTime - timeNow;
setTimeout(function() {
console.log('sessionStartTime: ' + sessionStartTime);
console.log('waitTime: ' + waitTime);
console.log('timeNow: ' + timeNow);
console.log('sessionStopTime: ' + sessionStopTime);
localStorage.removeItem("userId");
var userId = userIdDefault;
}, waitTime);
}
});
浏览器控制台日志:
第1页重新加载
main.js:sessionStartTime:1422232761
main.js:waitTime:1434 main.js:timeNow:1422232767
main.js:sessionStopTime:1422234201第二页重新加载
main.js:sessionStartTime:1422232761
main.js:waitTime:1416
main.js:timeNow:1422232785
main.js:sessionStopTime:1422234201userDataStored
对象{userId:“23”,登录:“login2”,firstName:“name”,lastName:“name”,email:“example@mail.com”...}用户id
“23”
答案 0 :(得分:0)
代码不起作用,因为localstorage中没有带密钥的数据 用户身份。用户标识是您存储在localstorage中的JSON对象中的密钥。
var userDataStored = JSON.parse(localStorage.getItem('userData'));
userDataStored.userId = null;
localStorage.setItem('userData', JSON.stringify(userDataStored ));