前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >jquery 本地存储 cookie 的基本用法

jquery 本地存储 cookie 的基本用法

作者头像
Devops海洋的渔夫
发布2019-05-30 21:45:51
2K0
发布2019-05-30 21:45:51
举报
文章被收录于专栏:Devops专栏

本地存储分为cookie,以及新增的localStorage和sessionStorage 。本篇章专门来讲讲 cookie

cookie

1、cookie 存储在本地,容量最大4k,在同源的http请求时携带传递,损耗带宽,可设置访问路径,只有此路径及此路径的子路径才能访问此cookie,在设置的过期时间之前有效。

jquery如果需要使用cookie,则需要一个插件js才可以使用。

本次采用最新维护中的Github采用的js。

Installation

Direct download

Download the script here and include it (unless you are packaging scripts somehow else):

代码语言:javascript
复制
<script src="/path/to/js.cookie.js"></script>

Or include it via jsDelivr CDN:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
Cookies.set('name', 'value');

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

代码语言:javascript
复制
Cookies.set('name', 'value', { expires: 7 });

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

代码语言:javascript
复制
Cookies.set('name', 'value', { expires: 7, path: '' });

Read cookie:

代码语言:javascript
复制
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined

Read all visible cookies:

代码语言:javascript
复制
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):

代码语言:javascript
复制
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:

代码语言:javascript
复制
Cookies.remove('name');

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
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.

代码语言:javascript
复制
// 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:

代码语言:javascript
复制
Cookies.set('name', { foo: 'bar' });

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

代码语言:javascript
复制
Cookies.get('name'); // => '{"foo":"bar"}'
代码语言:javascript
复制
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:

代码语言:javascript
复制
Cookies.getJSON('name'); // => { foo: 'bar' }
代码语言:javascript
复制
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的。

代码语言:javascript
复制
<!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,如下:

代码语言:javascript
复制
<!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>

浏览器访问如下:

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019.05.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • cookie
  • Installation
    • Direct download
    • Basic Usage
    • Namespace conflicts
    • JSON
    相关产品与服务
    内容分发网络 CDN
    内容分发网络(Content Delivery Network,CDN)通过将站点内容发布至遍布全球的海量加速节点,使其用户可就近获取所需内容,避免因网络拥堵、跨运营商、跨地域、跨境等因素带来的网络不稳定、访问延迟高等问题,有效提升下载速度、降低响应时间,提供流畅的用户体验。
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档