简体   繁体   English

sessionStorage未按预期工作

[英]sessionStorage isn't working as expected

Here is my code: 这是我的代码:

    sessionStorage.loggedIn = true;

    if (sessionStorage.loggedIn) {
        alert('true');
    }
    else {
        alert('false');
    }

Simple enough. 很简单。 There must be some small thing I'm not understanding about how JavaScript is evaluating these expressions. 必须有一些小事我不了解JavaScript如何评估这些表达式。 When I put sessionStorage.loggedIn = false , the "false" alert shows correctly. 当我将sessionStorage.loggedIn = false ,“false”警报正确显示。 However, when I change sessionStorage.loggedIn to true, the "false" alert still pops, even after clearing the session. 但是,当我将sessionStorage.loggedIn更改为true时,即使清除会话后,“false”警报仍会弹出。 What am I not getting right with this expression? 我对这个表达的态度是什么? It seems so simple, maybe I just need another pair of eyes on it. 看起来很简单,也许我只需要另外一双眼睛。

Try to change your code to 尝试将代码更改为

sessionStorage.setItem('loggedIn',JSON.stringify(true));

if (JSON.parse(sessionStorage.getItem('loggedIn'))) {
    alert('true');
}
else {
    alert('false');
}

and it should work consistently across all major browsers. 它应该在所有主流浏览器中保持一致。

The interface with the setItem / getItem methods is how the spec is written, so going that way is safer than using the shortcut of assigning properties. setItem / getItem方法的接口是规范的编写方式,因此采用这种方式比使用赋值属性的快捷方式更安全。 Also, sessionStorage , like localStorage is a textbased storage mechanism, and not meant for storing objects, so you need to wrap calls with JSON.parse and JSON.stringify to get the expected results across the board. 此外, sessionStoragelocalStorage一样,是一种基于文本的存储机制,并不适用于存储对象,因此您需要使用JSON.parseJSON.stringify包装调用以获得全面的预期结果。

Be aware that JSON.parse doesn't always play nice with undefined/null values, so it might be wise to do some type checking first. 请注意, JSON.parse并不总是与undefined / null值一起使用,所以最好先进行一些类型检查。

You can read the spec for the storage interface here 您可以在此处阅读存储接口的规范

Keys and Values in a WebStorage object (sessionStorage) must be strings. WebStorage对象(sessionStorage)中的键和值必须是字符串。 If they are not strings they "should" be converted to strings in the browser's implementation when you assign to sessionStorage. 如果它们不是字符串,则在分配给sessionStorage时,它们“应该”在浏览器的实现中转换为字符串。 If you evaluate against "true" or convert to boolean it will work fine. 如果您评估“true”或转换为布尔值,它将正常工作。

https://code.google.com/p/sessionstorage/ https://code.google.com/p/sessionstorage/

http://www.w3schools.com/html/html5_webstorage.asp http://www.w3schools.com/html/html5_webstorage.asp

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

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