jquery.cookie.js的介绍与使用方法

发布时间 - 2026-01-10 22:57:28    点击率:
目录
  • 一、什么是 cookie?
  • 二、jquery.cookie.js 使用方法
  • 三、完整实例
  • 四、小结和引深
  • 五、最后附上源代码
  • 六、总结

Cookie是由服务器端生成,发送给User-Agent(一般是浏览器),浏览器会将Cookie的key/value保存到某个目录下的文本文件内,下次请求同一网站时就发送该Cookie给服务器(前提是浏览器设置为启用cookie)。

例如购物网站存储用户曾经浏览过的产品列表,或者门户网站记住用户喜欢选择浏览哪类新闻。 在用户允许的情况下,还可以存储用户的登录信息,使得用户在访问网站时不必每次都键入这些信息?

怎么在js/jquery中操作处理cookie那?今天分享一个cookie操作类--jQuery.Cookie.js,是一个轻量级的Cookie管理插件。

一、什么是 cookie?

cookie 就是页面用来保存信息,比如自动登录、记住用户名等等。

cookie 的特点

  1. 同个网站中所有的页面共享一套 cookie
  2. cookie 有数量、大小限制
  3. 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); //删除一个cookie

2.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>

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。


# jquery.cookie.js使用  # jquery.cookie.js  # jquery.cookie.js 操作cookie实现记住密码功能的实现代码  # jquery.cookie.js使用指南  # 通过Jquery.cookie.js实现展示浏览网页的历史记录超管用  # javascript和jquery中cookie的设置方法  # 是一个  # 情况下  # 被称为  # 设置为  # 创建一个  # 源代码  # 客户端  # 序列化  # 还可以  # 也要  # 都能  # 是由  # 已被  # 设为  # 时间为  # 不支持  # 可以使用  # 可选  # 又能  # 时就 


相关栏目: 【 网站优化151355 】 【 网络推广146373 】 【 网络技术251813 】 【 AI营销90571


相关推荐: Laravel如何记录自定义日志?(Log频道配置)  做企业网站制作流程,企业网站制作基本流程有哪些?  Laravel队列由Redis驱动怎么配置_Laravel Redis队列使用教程  HTML透明颜色代码怎么让图片透明_给img元素加透明色的技巧【方法】  开心动漫网站制作软件下载,十分开心动画为何停播?  Bootstrap整体框架之CSS12栅格系统  如何快速启动建站代理加盟业务?  Python高阶函数应用_函数作为参数说明【指导】  原生JS获取元素集合的子元素宽度实例  Laravel中的Facade(门面)到底是什么原理  Laravel Debugbar怎么安装_Laravel调试工具栏配置指南  JavaScript模板引擎Template.js使用详解  如何在阿里云虚拟服务器快速搭建网站?  html5怎么画眼睛_HT5用Canvas或SVG画眼球瞳孔加JS控制动态【绘制】  如何在腾讯云服务器上快速搭建个人网站?  济南网站建设制作公司,室内设计网站一般都有哪些功能?  Laravel如何生成和使用数据填充?(Seeder和Factory示例)  如何在 Telegram Web View(iOS)中防止键盘遮挡底部输入框  如何确认建站备案号应放置的具体位置?  如何在VPS电脑上快速搭建网站?  利用 Google AI 进行 YouTube 视频 SEO 描述优化  如何构建满足综合性能需求的优质建站方案?  Windows Hello人脸识别突然无法使用  如何用AI一键生成爆款短视频文案?小红书AI文案写作指令【教程】  使用PHP下载CSS文件中的所有图片【几行代码即可实现】  5种Android数据存储方式汇总  Laravel怎么实现观察者模式Observer_Laravel模型事件监听与解耦开发【指南】  简单实现jsp分页  桂林网站制作公司有哪些,桂林马拉松怎么报名?  三星、SK海力士获美批准:可向中国出口芯片制造设备  制作电商网页,电商供应链怎么做?  Python正则表达式进阶教程_复杂匹配与分组替换解析  网站视频制作书签怎么做,ie浏览器怎么将网站固定在书签工具栏?  如何快速选择适合个人网站的云服务器配置?  如何快速搭建高效香港服务器网站?  PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑  Google浏览器为什么这么卡 Google浏览器提速优化设置步骤【方法】  如何为不同团队 ID 动态生成多个独立按钮  Laravel如何安装Breeze扩展包_Laravel用户注册登录功能快速实现【流程】  怎样使用JSON进行数据交换_它有什么限制  图片制作网站免费软件,有没有免费的网站或软件可以将图片批量转为A4大小的pdf?  Laravel模型事件有哪些_Laravel Model Event生命周期详解  如何在景安服务器上快速搭建个人网站?  如何在万网利用已有域名快速建站?  Python文件流缓冲机制_IO性能解析【教程】  移动端手机网站制作软件,掌上时代,移动端网站的谷歌SEO该如何做?  如何快速使用云服务器搭建个人网站?  如何基于PHP生成高效IDC网络公司建站源码?  制作无缝贴图网站有哪些,3dmax无缝贴图怎么调?  laravel怎么配置和使用PHP-FPM来优化性能_laravel PHP-FPM配置与性能优化方法