[英]LocalStorage is not updated when redirecting to another page in javascript
I'm trying to save a value in localStorage and then the page is redirected to another page.我试图在 localStorage 中保存一个值,然后页面被重定向到另一个页面。 but if the value was saved then I enter another value, when I go to the other page the value saved is the first one.但如果该值已保存然后我输入另一个值,当我 go 到另一页时,保存的值是第一个值。 for example, if the value was "red" in the localStorage then I enter the value "blue" after the page is redirected I find that the value saved is "red".例如,如果 localStorage 中的值为“red”,那么我在页面重定向后输入值“blue”,我发现保存的值是“red”。
<input type="text">
<button>click </button>
$('button').on('click', function () {
callbackLogFun();
});
function callbackLogFun() {
localStorage.setItem('user', JSON.stringify($('input').val()));
callRedirect();
}
function callRedirect() {
window.location.href = "sec-page.html";
}
and this how I call it on the second page这就是我在第二页上的称呼
localStorage.getItem('user');
If it's really a matter of not having enough time to save to localStorage before the page is redirected then you can make the calls to localStorage synchronous:如果在页面重定向之前确实没有足够的时间保存到 localStorage,那么您可以同步调用 localStorage:
const localStorageAsync = {
set: function (key, value) {
return Promise.resolve().then(function () {
localStorage.setItem(key, value);
});
},
get: function (key) {
return Promise.resolve().then(function () {
return localStorage.getItem(key);
});
}
};
localStorageAsync
.set('user', JSON.stringify($('input').val()))
.then(function() {
callRedirect();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.