简体   繁体   English

localStorage.setItem不会持久刷新

[英]localStorage.setItem not persisting on refresh

I'm trying to do a mega-simple setItem and getItem using HTML5 local storage. 我正在尝试使用HTML5本地存储来执行一个简单的setItem和getItem。 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'. 它输出一个警告框,上面写着'valueA'。 But when I comment out line 2 (which sets the item value) and refresh the page it just alerts 'null'. 但是当我注释掉第2行(设置项目值)并刷新页面时,它只是警告“空”。

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. 浏览器是Firefox 6,所以没问题。 Could it be something to do with calling it in the jquery document.ready? 可以在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! 如果有人能让我超过这个最初的障碍,我将非常感激,谢谢!

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. 它在Firefox和IE9中都不起作用,但它确实在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. 因此,我可以得出的结论是Firefox中的localStorage(至少6.0.2)和IE9在文件系统路径上运行时不起作用。 It does in Chrome. 它在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). Firefox和IE9需要一个“适当的”域来运行,大概是因为它们将localStorate对象与“域”相关联的方式比Chrome更严格(在Chrome中它不需要像域一样)。

I hope this has helped people as it's frustrated the hell out of me! 我希望这对人们有所帮助,因为它让我感到沮丧! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM