本地存储分为cookie,以及新增的localStorage和sessionStorage 。本篇章专门来讲讲 cookie
cookie
1、cookie 存储在本地,容量最大4k,在同源的http请求时携带传递,损耗带宽,可设置访问路径,只有此路径及此路径的子路径才能访问此cookie,在设置的过期时间之前有效。
jquery如果需要使用cookie,则需要一个插件js才可以使用。
已停止维护的Github地址:https://github.com/carhartl/jquery-cookie 访问下载jquery的cookie插件:http://plugins.jquery.com/cookie/
最新维护中的Github:https://github.com/js-cookie/js-cookie
本次采用最新维护中的Github采用的js。
Installation
Direct download
Download the script here and include it (unless you are packaging scripts somehow else):
Or include it via jsDelivr CDN:
Do not include the script directly from GitHub (http://raw.github.com/...). The file is being served as text/plain and as such being blocked in Internet Explorer on Windows 7 for instance (because of the wrong MIME type). Bottom line: GitHub is not a CDN.
在Github里面举例了很多的用法,如下:
Basic Usage
Create a cookie, valid across the entire site:
Create a cookie that expires 7 days from now, valid across the entire site:
Create an expiring cookie, valid to the path of the current page:
Read cookie:
Read all visible cookies:
Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not have been used when writing the cookie in question):
The cookie with the name foo
will only be available on .get()
if it's visible from where the code is called; the domain and/or path attribute will not have an effect when reading.
Delete cookie:
Delete a cookie valid to the path of the current page:
IMPORTANT! When deleting a cookie and you're not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie:
Note: Removing a nonexistent cookie does not raise any exception nor return any value.
Namespace conflicts
If there is any danger of a conflict with the namespace Cookies
, the noConflict
method will allow you to define a new namespace and preserve the original one. This is especially useful when running the script on third party sites e.g. as part of a widget or SDK.
Note: The .noConflict
method is not necessary when using AMD or CommonJS, thus it is not exposed in those environments.
JSON
js-cookie provides unobtrusive JSON storage for cookies.
When creating a cookie you can pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie will store the string representation of the object according to JSON.stringify
:
When reading a cookie with the default Cookies.get
api, you receive the string representation stored in the cookie:
When reading a cookie with the Cookies.getJSON
api, you receive the parsed representation of the string stored in the cookie according to JSON.parse
:
Note: To support IE6-7 (and IE 8 compatibility mode) you need to include the JSON-js polyfill: https://github.com/douglascrockford/JSON-js
看完上面的基础用法之后,这里来写上一个基础完整的cookie操作设置和读取的用例:
注意:需要运行在服务器环境,就是例如使用nginx服务。直接html在浏览器访问是不会生成cookie的。
访问浏览器如下:
下面再来读取cookie,如下:
浏览器访问如下: