35. jquery 本地存储 cookie 的基本用法

2019-05-11  本文已影响0人  Devops海洋的渔夫

本地存储分为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):

<script src="/path/to/js.cookie.js"></script>

Or include it via jsDelivr CDN:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

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:

Cookies.set('name', 'value');

Create a cookie that expires 7 days from now, valid across the entire site:

Cookies.set('name', 'value', { expires: 7 });

Create an expiring cookie, valid to the path of the current page:

Cookies.set('name', 'value', { expires: 7, path: '' });

Read cookie:

Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined

Read all visible cookies:

Cookies.get(); // => { name: 'value' }

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):

Cookies.get('foo', { domain: 'sub.example.com' }); // `domain` won't have any effect...!

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:

Cookies.remove('name');

Delete a cookie valid to the path of the current page:

Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!

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:

Cookies.remove('name', { path: '', domain: '.yourdomain.com' });

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.

// Assign the js-cookie api to a different variable and restore the original "window.Cookies"
var Cookies2 = Cookies.noConflict();
Cookies2.set('name', 'value');

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:

Cookies.set('name', { foo: 'bar' });

When reading a cookie with the default Cookies.get api, you receive the string representation stored in the cookie:

Cookies.get('name'); // => '{"foo":"bar"}'
Cookies.get(); // => { name: '{"foo":"bar"}' }

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:

Cookies.getJSON('name'); // => { foo: 'bar' }
Cookies.getJSON(); // => { name: { foo: 'bar' } }

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的。

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="jquery/js.cookie.js"></script>
    <script type="text/javascript">
        $(function(){

            // alert('hello');

            // 设置cookie 过期时间为7天,存放在当前路径下
            Cookies.set('name', 'value', { expires: 7, path: '' });
            Cookies.set('cookie1', 'test_value1', { expires: 7, path: '' });
            Cookies.set('cookie2', 'test_value2', { expires: 7, path: '' });

        })
    </script>
</head>
<body>
    <h1>测试Cookies</h1>
</body>
</html>

访问浏览器如下:

下面再来读取cookie,如下:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
    <script type="text/javascript" src="jquery/jquery-3.3.1.min.js"></script>
    <script type="text/javascript" src="jquery/js.cookie.js"></script>
    <script type="text/javascript">
        $(function(){

            // Read cookie:
            console.log( Cookies.get('name') ); // => 'value'
            console.log( Cookies.get('cookie1') ); // => test_value1
            console.log( Cookies.get('cookie2') ); // => test_value2
            console.log( Cookies.get('nothing') ); // => undefined

        })
    </script>
</head>
<body>
    <h1>测试Cookies</h1>
</body>
</html>

浏览器访问如下:

上一篇下一篇

猜你喜欢

热点阅读