sessionStorage isn't working as expected

落花浮王杯 提交于 2019-12-20 04:24:53

问题


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. When I put sessionStorage.loggedIn = false, the "false" alert shows correctly. However, when I change sessionStorage.loggedIn to true, the "false" alert still pops, even after clearing the session. What am I not getting right with this expression? It seems so simple, maybe I just need another pair of eyes on it.


回答1:


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. 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.

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.

You can read the spec for the storage interface here




回答2:


Keys and Values in a WebStorage object (sessionStorage) must be strings. If they are not strings they "should" be converted to strings in the browser's implementation when you assign to sessionStorage. If you evaluate against "true" or convert to boolean it will work fine.

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

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



来源:https://stackoverflow.com/questions/18319686/sessionstorage-isnt-working-as-expected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!