localStorage.setItem 刷新时不持久
我正在尝试使用 HTML5 本地存储来做一个超级简单的 setItem 和 getItem。但它似乎不起作用。这是有效的:
$(document).ready(function () {
localStorage.setItem('keyA', 'valueA');
var testA = localStorage.getItem('keyA');
alert(testA);
});
它输出一个警告框,上面写着“valueA”。但是当我注释掉第 2 行(设置项目值)并刷新页面时,它只会警告“null”。
为什么价值不持久?就好像它根本没有被真正存储一样。
浏览器是Firefox 6,所以没问题。这可能与在 jquery document.ready 中调用它有关吗?我用谷歌搜索过,但没有看到任何相关内容。
如果有人能让我克服这个最初的障碍,我将不胜感激,谢谢!
I'm trying to do a mega-simple setItem and getItem using HTML5 local storage. It just doesn't seem to work though. This works:
$(document).ready(function () {
localStorage.setItem('keyA', 'valueA');
var testA = localStorage.getItem('keyA');
alert(testA);
});
It outputs an alert box saying 'valueA'. But when I comment out line 2 (which sets the item value) and refresh the page it just alerts 'null'.
Why is the value not persisting? It's like it's just not actually getting stored at all.
The browser is Firefox 6, so no problem there. Could it be something to do with calling it in the jquery document.ready? I've googled but couldn't see anything about that.
If anyone could get me over this initial hurdle I'd be most grateful, thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,经过一番挫折后,我找到了解决方案。基本上,我只是从文件系统在本地运行它作为“快速”概念证明。它在 Firefox 和 IE9 中都不起作用,但在 Chrome 中却可以。
我最终做的是在真实的域上尝试这个,这似乎已经成功了。
所以我可以得出的结论是,Firefox(至少 6.0.2)和 IE9 中的 localStorage 在文件系统路径上运行时不起作用。 Chrome 中确实如此。 Firefox 和 IE9 需要一个“适当的”域来运行,大概是因为它们将 localStorate 对象与“域”关联起来的方式比 Chrome 更严格(在 Chrome 中,它不需要是一个域)。
我希望这对人们有帮助,因为这让我很沮丧! :)
Okay, after a lot of frustration I have the solution. Basically, I was running this locally just from the filesystem as a 'quick' proof of concept. It didn't work in Firefox nor in IE9 but it did work in Chrome.
What I ended up doing was trying this on a real domain, and that seems to have done the trick.
So the conclusion I can draw is that localStorage in Firefox (6.0.2 at least) and IE9 does not work when run on a file-system path. It does in Chrome. Firefox and IE9 require a 'proper' domain to run from, presumably because they are more strict than Chrome in the way they associate the localStorate object to a 'domain' (in Chrome it doesn't need to be a domain as such).
I hope this has helped people as it's frustrated the hell out of me! :)