jquery.cookie.js的介绍与使用方法
作者:朱羽佳
Cookie是由服务器端生成,发送给User-Agent(一般是浏览器),浏览器会将Cookie的key/value保存到某个目录下的文本文件内,下次请求同一网站时就发送该Cookie给服务器(前提是浏览器设置为启用cookie)。
例如购物网站存储用户曾经浏览过的产品列表,或者门户网站记住用户喜欢选择浏览哪类新闻。 在用户允许的情况下,还可以存储用户的登录信息,使得用户在访问网站时不必每次都键入这些信息?
怎么在js/jquery中操作处理cookie那?今天分享一个cookie操作类--jQuery.Cookie.js,是一个轻量级的Cookie管理插件。
一、什么是 cookie?
cookie 就是页面用来保存信息,比如自动登录、记住用户名等等。
cookie 的特点
- 同个网站中所有的页面共享一套 cookie
- cookie 有数量、大小限制
- cookie 有过期时间jquery.cookie.js 是一款轻量级的 cookie 插件,可以读取,写入和删除 cookie。本文主要针对
jquery.cookie.js 的用法进行详细的介绍。
二、jquery.cookie.js 使用方法
Cookies
定义:让网站服务器把少量数据储存到客户端的硬盘或内存,从客户端的硬盘读取数据的一种技术;
下载与引入:jquery.cookie.js基于jquery;先引入jquery,再引入:jquery.cookie.js;
下载:http://plugins.jquery.com/cookie/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.cookie.js"></script>
使用:
1.添加一个"会话cookie"
$.cookie('the_cookie', 'the_value');这里没有指明 cookie有效时间,所创建的cookie有效期默认到用户关闭浏览器为止,所以被称为 “会话cookie(session cookie)”。
2.创建一个cookie并设置有效时间为 7天
$.cookie('the_cookie', 'the_value', { expires: 7 });这里指明了cookie有效时间,所创建的cookie被称为“持久 cookie (persistent cookie)”。注意单位是:天;
3.创建一个cookie并设置 cookie的有效路径
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });在默认情况下,只有设置 cookie的网页才能读取该 cookie。如果想让一个页面读取另一个页面设置的cookie,必须设置cookie的路径。cookie的路径用于设置能够读取 cookie的顶级目录。将这个路径设置为网站的根目录,可以让所有网页都能互相读取 cookie (一般不要这样设置,防止出现冲突)。
4.读取cookie
$.cookie('the_cookie');5.删除cookie
$.cookie('the_cookie', null); //通过传递null作为cookie的值即可6.可选参数
$.cookie('the_cookie','the_value',{
expires:7,
path:'/',
domain:'jquery.com',
secure:true
}) expires:(Number|Date)有效期;设置一个整数时,单位是天;也可以设置一个日期对象作为Cookie的过期日期;这个地方也要注意,如果不设置这个东西,浏览器关闭之后此cookie就失效了
path:(String)创建该Cookie的页面路径;cookie值保存的路径,默认与创建页路径一致。
domain:(String)创建该Cookie的页面域名;默认与创建页域名一样。 这个地方要相当注意,跨域的概念,如果要主域名二级域名有效则要设置 ".xxx.com"
secure:一个布尔值,表示传输cookie值时,是否需要一个安全协议。(Booblean)如果设为true,那么此Cookie的传输会要求一个安全协议,例如:HTTPS;
raw: true:默认值:false。 默认情况下,读取和写入cookie的时候自动进行编码和解码(使用encodeURIComponent编码,decodeURIComponent解码)。
要关闭这个功能设置raw: true即可。
三、完整实例
一个完整设置与读取cookie的页面代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery学习2</title>
<script src="jQuery.1.8.3.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#username").val($.cookie("username"));
if ($.cookie("like") == "刘德华") {
$(":radio[value='刘德华']").attr("checked", 'checked')
}
else {
$(":radio[value='张学友']").attr("checked", 'checked')
}
$(":button").click(function () {
$.cookie("username", $("#username").val(), {
path: "/", expires: 7
})
$.cookie("like", $(":radio[checked]").val(), {
path: "/", expiress: 7
})
})
})
</script>
</head>
<body>
<p><input type="text" id="username" value="" /></p>
<p>
<input type="radio" name="like" value="刘德华" />刘德华
<input type="radio" name="like" value="张学友" />张学友
</p>
<p><input type="button" value="保存" /></p>
</body>
</html>cookie本质上是一个txt文本,因此只能够存入字符串,对象通常要序列化之后才能存入cookie,而取的时候要反序列才又能得到对象。
$(function () {
if ($.cookie("o") == null) {
var o = { name: "张三", age: 24 };
var str = JSON.stringify(o); //对序列化成字符串然后存入cookie
$.cookie("o", str, {
expires:7 //设置时间,如果此处留空,则浏览器关闭此cookie就失效。
});
alert("cookie为空");
}
else {
var str1 = $.cookie("o");
var o1 = JSON.parse(str1); //字符反序列化成对象
alert(o1.name); //输反序列化出来的对象的姓名值
}
})一个轻量级的cookie插件,可以读取、写入、删除cookie。
四、小结和引深
1.jQuery操作cookie的插件,大概的使用方法如下:
$.cookie('the_cookie'); //读取Cookie值
$.cookie('the_cookie', ‘the_value'); //设置cookie的值
$.cookie('the_cookie', ‘the_value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true});//新建一个cookie 包括有效期 路径域名等
$.cookie('the_cookie', ‘the_value'); //新建cookie
$.cookie('the_cookie', null); //删除一个cookie2.jquery设置cookie过期时间与检查cookies是否可用:
//让cookies在x分钟后过期
var date = new date();
date.settime(date.gettime() + (x * 60 * 1000));
$.cookie(‘example', ‘foo', { expires: date });
$.cookie(‘example', ‘foo', { expires: 7});//检查当前浏览器不支持或Cookie已被禁用呢?可以使用以下js代码:
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled) {
//没有启用cookie
alert("没有启用cookie ");
} else{
//已经启用cookie
alert("已经启用cookie ");
}五、最后附上源代码
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};六、总结
jQuery.cookie.js 是一个用于设置、读取和删除浏览器cookie的jQuery插件。以下是一些常用的方法和示例:
设置cookie:
$.cookie('name', 'value'); // 设置一个名为 'name' 值为 'value' 的cookie
$.cookie('name', 'value', { expires: 7 }); // 设置一个有7天过期时间的cookie读取cookie:
var name = $.cookie('name'); // 获取名为 'name' 的cookie值删除cookie:
$.cookie('name', null); // 删除名为 'name' 的cookie读取所有cookie:
var allCookies = $.cookie(); // 返回一个包含所有cookie的对象
设置cookie属性:
$.cookie('name', 'value', {
expires: 7, // 设置cookie有效期为7天
path: '/', // 设置cookie在整个站点有效
domain: 'jquery.com', // 设置cookie对jquery.com域及其子域有效
secure: true // 设置cookie仅在HTTPS下传输
});确保在使用这些方法之前,你已经在页面中引入了jQuery库和jQuery.cookie.js。例如:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。
