Cookie与Web存储

时间:2016-01-07 07:13:00

标签: javascript html5

我正在创建一个项目,我希望保存用户到达的最后一个级别,以便他们可以在下次离开的地方继续。我想知道我是否应该使用cookie或网络存储,以及使用每个存储的原因。例如,一个是影响性能,一个是通常启用/禁用的,是现代浏览器不支持的一个,等等。

我也有兴趣知道除了这两个之外还有其他选择我可以使用,以及它们的优点和缺点是什么。

谢谢!

2 个答案:

答案 0 :(得分:0)

他们有完全不同的目的。 Cookie可从服务器获得,而Web存储仅供客户端使用。每个请求,cookie都将通过HTTP标头发送到服务器。当服务器不需要数据时,不需要这样做。在这种情况下,Web Storage可能就是您的选择。

这一切都取决于您想要访问数据的人。

Web Storage提供了一种永久存储数据的方法(直到用户清除其浏览器缓存),而Cookie设置为在一定时间后过期。

Web存储也更适合存储大块数据,例如完整的JSON数据表示(最多5MB)。从IE8开始支持Web存储,因此应该没问题。

答案 1 :(得分:0)



**Cookies**
Pros
1. Legacy support (it's been around forever)
2. Persistent data
3. Expiration dates

Cons
1. Each domain stores all its cookies in a single string, which can make parsing data difficult
2. Data is unencrypted.
3. small in size, cookies are sent with every HTTP request
4. Limited size (4KB)
5. SQL injection can be performed from a cookie

**Local storage / Web storage**
Pros
1. Support by most modern browsers
2. Persistent data that is...
3. stored directly in the browser
4. Same-origin rules apply to local storage data
5. Is not sent with every HTTP request
6. ~5MB storage per domain (that's 5120KB)

Cons
Not supported by anything before:
1. IE 8
2. Firefox 3.5
3. Safari 4
4. Chrome 4
5. Opera 10.5
6. iOS 2.0
7. Android 2.0
8. If the server needs stored client information you purposefully have to send it. [3]



Based on my comparison I think that local storage is the logical successor of cookies for storing client-side data. While cookies were originally created as a work-around, local storage has been designed with a purpose.

Local storage is easier to work with because you don't have to parse a string to get data. Instead you can make a call for the variable name and it's value is returned. The same applies with creating and deleting data as well.

For saving client-side data I believe local storage wins. As someone on the stackoverflow boards pointed out however, if your server needs information from a client cookies will be a better solution. But if you just want to save user-prefs, num vists, or other stuff like that choose local storage.




相关问题