[英]Storing user data in an object in local storage
我正在創建一個關於創建網站的學校項目。 我已經設法在注冊帳戶時將用戶數據保存到本地存儲中。 當我昨天嘗試使用以下代碼時,代碼可以正常工作:在我以用戶身份登錄后,鍵“currentUser”將出現在本地存儲中。 但是,在我清除了本地存儲(陣列中的用戶太多)並再次重新運行代碼后,currentUser將不再顯示在本地存儲中。 這是我的代碼:從編輯個人資料頁面:`
<script>
var currentUser=null;
document.addEventListener("DOMContentLoaded",loadUserData);
function loadUserData() {
currentUser = localStorage.getItem("currentUser");
if(currentUser!=null) {
currentUser = JSON.parse(currentUser);
}
}
</script>
以上代碼加上登錄html中的代碼將currentUser顯示為本地存儲中的密鑰(應該僅在以當前用戶身份登錄時顯示)從登錄頁面:
function checkUser(ev) {
ev.preventDefault();
var status=false;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<userList.length;i++) {
var u=userList[i];
console.log(u.username);
console.log(u.password);
if (u.username==username && u.password==password){
status=true;
localStorage.setItem("currentUser",username);
currentUser=userList[i];
break;
}
}
if (status==true){
location.href="EditProfile.html";
}
}
在本地存儲中出現的只是關鍵的currentUser,但它的值是空的。 我想在用戶登錄后顯示當前存儲中顯示的currentUser的數據信息,以便我可以在編輯配置文件和配置文件頁面中顯示用戶詳細信息。
我希望在本地存儲中看到的內容:
key value
currentUser {"username":"staff3","name":"stella ","password":"123","rpassword":"123,"email":"g@gmail.com"}
在本地存儲中顯示的內容:
key value
currentUser //nth showed up here
這是問題所在:
LocalStorage僅存儲字符串。 如果要存儲對象,可以使用
JSON.stringify(object)
所以在你的情況下,你需要:
localStorage.setItem("currentUser",JSON.stringify(userList[i]));
希望有所幫助!
干脆就這么做
function checkUser(ev) {
ev.preventDefault();
var status=false;
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
for(var i=0;i<userList.length;i++) {
var u=userList[i];
console.log(u.username);
console.log(u.password);
if (u.username==username && u.password==password){
console.log('Logged In');//check whether this console appears or not
localStorage.setItem("currentUser",userList[i]);//store whole data of logged user
currentUser=userList[i];
status=true;
break;
}
}
if (status==true){
location.href="EditProfile.html";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.