JavaScript操作Cookie笔记

    最近初涉前端,重新对前端有深刻的认识,以前就觉得前端就是简单的敲敲hml标签,设置下样式,最近手机app要用H5和JS开发,然后就一头扎进前端的海洋里了,顿时懵了,太多的知识点,项目又压的紧,幸亏公司有做前端的工程师,但是需要我做JS,于是开始了JS从零到精通的路线开始学习,过了几天我觉得我的学习方法有问题,就是在对于项目无谓的地方浪费了太多的时间,因为公司是小公司,项目也是小项目,要的是开发速度,所以如果想要把一个自己不曾涉及到的领域学的精通,不能再像学校里逮着一门课学习几个月而且到最后发现学的都是理论,操作能力依然很差,在公司里学习就必须一个知识点一个知识点的学习,学一点就要会一点,自己就要进步一点,对所学领域就要精通一点,随着岁月的沉淀慢慢的向大神靠拢。这是作为小白的我对于快速学习的一点看法,在自己身上实行一段时间看看是否正确,还请有经验的大牛指导如何更好的学习。下面进入正题。

    可以说今天我才真正的上网找有关JS操作Cookie的资料进行学习,网上大牛的博客写的真是太好了,一看就一目了然。这里贴出几篇觉得总结的较好的博文链接

从最简单说起Cookie为何物,JS如何进行操作:http://www.cnblogs.com/shoupifeng/archive/2011/11/25/2263892.html

 这篇博文里提到了W3School的代码,这里我也把W3School的链接也贴出来吧:W3School关于Cookie的讲解 

 一遍看一遍敲代码进行测试,第一次亲手操作Cookie基本上是照抄代码,自己最初的理解Cookie是一种固定格式的字符串,看到别人写的setCookie()和getCookie()方法觉得可以拿来封装成JS库收入囊中,百度了下,找到了一个比较好的插件cookie.js

把工程下载下来后里面有个README.md文件,内容如下(我简单的翻译了下):

<span style="font-size:14px;"><span style="font-size:14px;">#  cookie.js – simplifying cookies in JavaScript [![Build Status](https://travis-ci.org/florian/cookie.js.png?branch=master)](https://travis-ci.org/florian/cookie.js)

cookie.js is a tiny JavaScript library that simplifies cookies. It is capable of setting, getting and removing cookies, accepts a variety of parameters, and supports chaining.  It doesn't have any dependencies and minified+gzipped it's only 0.9 KB small.
//翻译:简化cookie的cookie.js是一个很小的JS库,包含了设置、获取和删除cookie方法,接收各样的参数,并且支持链接,不依赖于任何文件,迷你版压缩后仅仅只有0.9KB
## Why would you want to use it?
Working with cookies in JavaScript sucks. `document.cookie` is definitely one of the ugly parts of JavaScript. This library aims to provide an easy and nevertheless powerful way to use cookies.

## Usage

Download [cookie.min.js](https://raw.github.com/florian/cookie.js/master/cookie.min.js) and include it in your HTML document, this will add a global object called `cookie`:
//翻译:下载 cookie.min.js 并且通过下列方式包含进你的HTML文件,这样就会添加一个全局对象:"cookie"
```html
<script src="cookie.min.js"></script>
```

Alternatively you can use a JavaScript package manager to add it to your project:
```sh
$ bower install cookie --save
$ jam install cookie
$ npm install cookie_js --save
```

---

cookie.js supports AMD and CommonJS. So if you want to include cookie.js dynamically, you can just require it with any AMD / CommonJS loader, for example [RequireJS](http://requirejs.org/) for AMD.
Follow the instructions of your loader to include cookie.js.

---

After that you can call any of methods that are explained in the following.

## cookie.set
You can use the `cookie.set` method to set cookies. The value will automatically be escaped for you.
//设置cookie单个值的方法
```javascript
cookie.set('key', 'value');
```

*Note: Values will be casted to string, so setting a number will work. However, the value will be a string when getting the cookie.*

You can also set several values at once:
//设置</span><span style="font-family:Microsoft YaHei;">cookie多个值的方法
```javascript
cookie.set({
   key1: 'value1',
   key2: 'value2'
});
```

If you need more options, like setting the expiry date, you can add an object with options as the last parameter:
//翻译:如果你需要更多的选择,比如设置 有效期限,你可以加入一个选择对象作为最后一个参数:
```javascript
cookie.set('key', 'value', {
   expires: 7, // expires in one week
});

cookie.set({
   key1: 'value1',
   key2: 'value2'
}, {
   expires: 7
})
```

The following fields can be added to the mentioned object:
//翻译:可以添加下面提到的对象作为参数
| key | value | default value |
|:--|:--|:--|
| `expires` |  Either a `number` containing the days until the expiry, a date in the `GMTString` format or a `date object`. | Expires when the browser is closed. |
| `domain` |  A `string` that specifies the domain that can access the cookie. | The current domain. |
| `path` | A `string` that limits the access of the cookie to that path. | The current path. |
| `secure` | A `boolean` indicating whether the cookie shall only be accessable over a secure connection or not. | `false` |

You can customize the default settings by manipulating `cookie.defaults`.
//翻译:你可以通过操纵“cookie.defaults”定制默认的设置
```javascript
cookie.defaults.expires = 7;
cookie.defaults.secure = true;
```

Most people will prefer specifying the expiry date in days, but if you want to specify the expiry date in minutes, then you can configure `cookie.expiresMultiplier`:
//大多数人喜欢用天指定cookie过期的期限,但是如果你想指定期限为几分钟,那么你可以配置`cookie.expiresMultiplier`
```javascript
cookie.expiresMultiplier = 60; // Seconds.
cookie.expiresMultiplier = 60 * 60; // Minutes.
cookie.expiresMultiplier = 60 * 60 * 24; // Hours.
```

## cookie.get
This method allows you to retrieve your cookies, you can use it by simply passing the key of the cookie:
//下面是获取cookie的一个值,适用于获取简单的key,返回的是一个字符串
```javascript
cookie.get('key');
```

Passing just one key like this will return a string, containing the value of the cookie. You can also pass an array of keys:
//下面是通过数组获取多个key的值,返回的是一个对象
```javascript
cookie.get(['key1', 'key2']);
```

This will always return an object. The keys of this object will be the keys you passed and the values are the corresponding values.

In case you want to add a default value you can use the second parameter. The default value will be returned if the cookie*(s)* could not be found:
//下面是取一个key的值,当你所要取的key不存在的时候返回default value
```javascript
cookie.get('key', 'default value');
```

This also works with several keys:
//多个值同理
```javascript
cookie.get(['key1', 'key2'], 'default value');
```

`cookie()` is a shortcut for `cookie.get()`.
//翻译:cookie()是一个cookie.get()的快捷方法
```javascript
cookie.get('key');
// is the same as
cookie('key');
```

## cookie.all

```javascript
var cookies = cookie.all();
```

To get all of the currently saved cookies simply call `cookie.all`. In this case the variable `cookies` will return an object with all the current cookies.
//翻译:获取当前保存的所有cookie简单的方法是调用coolie.all。这个方法执行时变量cookies会返回一个包含当前所有cookie的对象
## cookie.remove

This method allows you to remove cookies. It accepts an infinite number of keys or an array of keys.
//翻译:这个方法允许你删除cookie,它接受无限数量的key或者是key的数组
```javascript
cookie.remove('key');
cookie.remove('key1', 'key2');
cookie.remove(['key1', 'key2']);
```

## cookie.empty

Sometimes you may want to remove all cookies. Simply call `cookie.empty()` and every cookie will be removed.
//翻译:有时你或许想删除所有的cookie,只需要简单的调用cookie.empty()方法并且所有的cookie都将被删除
## cookie.enabled

This method allows you to test if the cookies are enabled. It returns `true` if you can work with cookies and `false` if you cannot. You might want to use a fallback if they are disabled:
//翻译:这个方法允许你去测试如果这个cookie已经被激活,如果你可以操作cookie返回true,否则返回false
```javascript
if (cookie.enabled()) {
   // Do stuff with cookies
} else {
   // Display error message or use localStorage
}
```

## cookie.setDefault

This method works just like `cookie.set` and accepts the same arguments, but it
only sets those cookies that don't have a value yet allowing you to specify
default values.
//这个方法用起来很像cookie.set而且接收相同的参数,但是只能设置那些没有值的cookie,原先有值的设置了也不起作用
```javascript
cookie.set('a', '1');
cookie.setDefault({
   a: '2',
   b: '2'
});

cookie.get(['a', 'b']); // {a: "1", b: "2"}
```

## Chaining

The methods `set`, `remove` and `empty` return the cookie object and therefore enable chaining.
//set、remove、empty方法返回cookie对象而且允许链接
```javascript
cookie.empty().set('key1', 'value1').set('key2', 'value2').remove('key1');
```

## A word on encoding

cookie.js sensibly encodes / decodes values and should work just fine with most
server side frameworks. However sometimes there are weird server side encodings,
for example PHP escapes spaces with `+` for historic reasons.
This library can't handle all of those cases at the same time so if you notice
you need a custom decoding function you can overwrite `cookie.utils.decode`.
//cookie.js能聪明的解码/编码值并且能在大部分服务器和框架上工作。但是有时奇怪的服务器编码,比如
PHP escapes spaces with `+` for historic reasons.
//这个库是不能处理这些事件,如果你注意了,你可以重写‘cookie.utils.decode’方法定制你需要的解码功能
 ```javascript
// For example
cookie.utils.decode = function (value) {
   return decodeURIComponent(value).replace('+', ' ');
};
```

- - -

## Wiki pages

- [Contribute](https://github.com/florian/cookie.js/wiki/Contribute)
- [Changelog](https://github.com/florian/cookie.js/wiki/Changelog)
</span></span>


关于cookie的知识也是相当的多,对于一个熟悉而又陌生的领域短时间内我不求甚解,留给以后的岁月慢慢学习吧,下面贴出一个我测试的代码:通过使用cookie.min.js在两个html页面之间传值

这个是A Page Cookie

<span style="font-size:14px;"><span style="font-size:14px;"><!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>A Page Cookie</title>
		<script type="text/javascript" src="../js/jquery.js"></script>
		<script type="text/javascript" src="../js/cookie.min.js"></script>
	</head>

	<body>
		<script type="text/javascript">
			function showInfo(obj) {
				cookie.set({
					id: obj.getAttribute("id"),
					name: obj.getAttribute("name")
				});
			}
		</script>
		<ul>
			<li><a class="check" href="BPageCookie.html" name="a" id="goods1" οnclick="showInfo(this)">商品1商品1商品1</a></li>
			<li><a class="check" href="BPageCookie.html" name="b" id="goods2" οnclick="showInfo(this)">商品2商品2商品2</a></li>
			<li><a class=" check " href="BPageCookie.html " name="c " id="goods3 " οnclick="showInfo(this)">商品3商品3商品3</a>
			</li>
			<li><a class="check" href="BPageCookie.html" name="d" id="goods4" οnclick="showInfo(this)">商品4商品4商品4</a></li>
			<li><a class=" check " href="BPageCookie.html " name="e " id="goods5 " οnclick="showInfo(this)">商品5商品5商品5</a>
			</li>
		</ul>

	</body>

</html></span></span>

下面是BPageCookie

<span style="font-size:14px;"><!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>B Page Cookie</title>
		<script type="text/javascript" src="../js/jquery.js"></script>
		<script type="text/javascript" src="../js/cookie.min.js"></script>
	</head>

	<body>
		<script type="text/javascript">
			$(function() {
				("#title").html("商品" + cookie.get('id') + "的详情");
				//获取多个值,返回一个object
				//var c = cookie.get(['id', 'name']);
				//$("#title").html("商品" + c.id + "的详情");
				//获取一个值,如果找不到的话返回默认值
				//var c=cookie.get('ic', '3');
				//$("#title").html("商品" + c + "的详情");
				//删除一个cookie
				//cookie.remove('id');
				//获取一个值, 如果找不到的话返回默认值
				//var c = cookie.get('id', '3');
				//$("#title").html("商品" + c + "的详情");
			})
		</script>
		<h1 id="title"></h1>
	</body>

</html></span>


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值