我正在尝试保存登录用户的一些数据。当我试图访问在上一页中创建的单例数据时,单例会被重新初始化,所有数据都会丢失
这是我的单例代码:在profile.js 中
const databaseURL = "************************";
class ProfileOBJ{
async fetchProfile(id){
var profile = await (await fetch(databaseURL +'/user/'+id)).json();
console.log("Json response");
console.log(profile)
this.parseProfile(profile)
}
async login(id){
if(this.loggedIn){
return;
}
await this.fetchProfile(id)
this.loggedIn = true;
}
parseProfile(profile){
this.moderator = profile.moderator;
this.questionData = profile.questionData;
this.progressionData = profile.progressionData;
this.id = profile._id;
this.institution = profile.institution;
}
constructor() {
}
}
window.Profile = class{
static instance;
constructor() {
if (this.instance == undefined) {
this.instance = new ProfileOBJ();
}
}
getInstance() {
return this.instance;
}
}
我将此文件导入到我的HTML文件中,如下所示:
<script src="profile.js"></script>
我用它就像:
let user = (new Profile()).getInstance();
console.log(user);
当我路由到其他页面时,如:
window.location.href = "./secondPage.html";
类被重新初始化,因此所有数据都会丢失
我想知道是否有任何方法可以从不同的HTML页面访问这些信息
在将session_start()
与PHP 一起使用时,我以前做过的最简单的方法
https://www.php.net/manual/en/function.session-start.php
或者,您应该能够使用localStorage
或sessionStorage
来完成此操作
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
尽管我自己还没有尝试过。