`
天梯梦
  • 浏览: 13640316 次
  • 性别: Icon_minigender_2
  • 来自: 洛杉矶
社区版块
存档分类
最新评论

javascript / jquery 操作 cookie

阅读更多

什么是Cookie?

谓Cookie,是网页 通过浏览器保 存在用户本地计算机 上的一小段数据 。用户再次访问该网页的时候,浏览器会将这一小段数据发送给该网页。Cookie是网景公司的前雇员Lou Montulli在1993年3月的发明。

 

Cookie 最典型的应用是判定注册用户是否已经登录网站。用户可能会得到提示,是否在下一次进入此网站时保留用户信息以便简化登录手续,也就是所谓“保存登录信息” 或“记住我”,这些所谓“记忆”都是用Cookie保存的。另一个重要应用场合是“购物车” 之类处理。用户可能会在一段时间内在同一家网站的不同页面中选择不同的商品,网页把这些信息会写入Cookie,以便在最后付款时提取信息。

Cookie里面都有些什么?

Cookie一般包含至少下面3项内容。

  • 具体数据的名称和值
  • 过期日
  • 针对网页的域名和路径

如果没有指定过期日,Cookie在浏览器关闭时过期;如果想Cookie永不过期,就把过期日指定为当前日期加上一万年好了(^_*)。

Cookie究竟有多大?

根据Internet标准RFC 2109, HTTP State Management Mechanism

  • 每个Cookie可以有4096字节(4KB)
  • 一个浏览器至少保存300个Cookie
  • 一个站点的Cookie数量不超过20个

当然,不同浏览器可以有自己的设置,可以放宽上面的这些限制。上面的只是最小限制。

 

 

  我们先要学一学 Cookie 的基本知识。

  每个 Cookie 都是这样的: <cookie >=< >

   <cookie > 的限制与 javascript 的命名限制大同小异,少了 不能用 javascript 关键字 ,多了 只能用可以用在 URL 编码中的字符 。后者比较难懂,但是只要你只用字母和数字命名,就完全没有问题了。 < > 的要求也是 只能用可以用在 URL 编码中的字符

  每个 Cookie 都有失效日期,一旦电脑的时钟过了失效日期,这个 Cookie 就会被删掉。我们不能直接删掉一个 Cookie ,但是可以用设定失效日期早于现在时刻的方法来间接删掉它。

  每个网页,或者说每个站点,都有它自己的 Cookies ,这些 Cookies 只能由这个站点下的网页来访问,来自其他站点或同一站点下未经授权的区域的网页,是不能访问的。每一 ”Cookies 有规定的总大小(大约 2KB ),一超过最大总大小,则最早失效的 Cookie 先被删除,来让新的 Cookie“ 安家

  现在我们来学习使用 documents.cookie 属性。

  如果直接使用 documents.cookie 属性,或者说,用某种方法,例如给变量赋值,来获得 documents.cookie 的值,我们就可以知道在现在的文档中有多少个 Cookies ,每个 Cookies 的名字,和它的值。例如,在某文档中添加 “document.write(documents.cookie)” ,结果显示:

name=kevin; email=kevin@kevin.com; lastvisited=index.html

这意味着,文档包含 3 Cookies name, email lastvisited ,它们的值分别是 kevin, kevin@kevin.com index.html 。可以看到,两个 Cookies 之间是用分号和空格隔开的,于是我们可以用 cookieString.split('; ') 方法得到每个 Cookie 分开的一个数组(先用 var cookieString = documents.cookie )。

  设定一个 Cookie 的方法是对 documents.cookie 赋值。与其它情况下的赋值不同,向 documents.cookie 赋值不会删除掉原有的 Cookies ,而只会增添 Cookies 或更改原有 Cookie 。赋值的格式:

documents.cookie = 'cookieName=' + escape('cookievalue')
+ ';expires=' + expirationDateObj.toGMTString();

 

是不是看到头晕了呢? cookieName 表示 Cookie 的名称, cookievalue 表示 Cookie 的值, expirationDateObj 表示储存着失效日期的日期对象名,如果不需要指定失效日期,则不需要第二行。不指定失效日期,则浏览器默认是在关闭浏览器(也就是关闭所有窗口)之后过期。

  首先 escape() 方法:为什么一定要用?因为 Cookie 的值的要求是 只能用可以用在 URL 编码中的字符 。我们知道 “escape()” 方法是把字符串按 URL 编码方法来编码的,那我们只需要用一个 “escape()” 方法来处理输出到 Cookie 的值,用 “unescape()” 来处理从 Cookie 接收过来的值就万无一失了。而且这两个方法的最常用途就是处理 Cookies 。其实设定一个 Cookie 只是 “documents.cookie = 'cookieName=cookievalue'” 这么简单,但是为了避免在 cookievalue 中出现 URL 里不准出现的字符,还是用一个 escape() 好。


  然后 “expires” 前面的分号:注意到就行了。是分号而不是其他。


  最后 toGMTString() 方法:设定 Cookie 的时效日期都是用 GMT 格式的时间的,其它格式的时间是没有作用的。

  现在我们来实战一下。设定一个 “name=rose” Cookie ,在 3 个月后过期。

var expires = new Date();
expires.setTime(expires.getTime() + 3 * 30 * 24 * 60 * 60 * 1000);
/* 三个月 x 一个月当作 30 天 x 一天 24 小时
x 一小时 60 分 x 一分 60 秒 x 一秒 1000 毫秒 */
documents.cookie = 'name=rose;expires=' + expires.toGMTString();

 

为什么没有用 escape() 方法?这是因为我们知道 rose 是一个合法的 URL 编码字符串,也就是说, 'rose' == escape('rose') 。一般来说,如果设定 Cookie 时不用 escape() ,那获取 Cookie 时也不用 unescape()

  再来一次:编写一个函数,作用是查找指定 Cookie 的值。

function getCookie(cookieName) {
var cookieString = documents.cookie;
var start = cookieString.indexOf(cookieName + '=');
// 加上等号的原因是避免在某些 Cookie 的值里有
// 与 cookieName 一样的字符串。
if (start == -1) // 找不到
return null;
start += cookieName.length + 1;
var end = cookieString.indexOf(';', start);
if (end == -1) return unescape(cookieString.substring(start));
return unescape(cookieString.substring(start, end));
}
 

这个函数用到了字符串对象的一些方法,如果你不记得了(你是不是这般没记性啊),请快去查查。这个函数所有的 if 语句都没有带上 else ,这是因为如果条件成立,程序运行的都是 return 语句,在函数里碰上 return ,就会终止运行,所以不加 else 也没问题。该函数在找到 Cookie 时,就会返回 Cookie 的值,否则返回 “null”

  现在我们要删除刚才设定的 name=rose Cookie

var expires = new Date();
expires.setTime(expires.getTime() - 1);
documents.cookie = 'name=rose;expires=' + expires.toGMTString();

 

可以看到,只需要把失效日期改成比现在日期早一点(这里是早 1 毫秒),再用同样的方法设定 Cookie ,就可以删掉 Cookie 了。

 

实例:

 

<html>
<head>
<script type="text/javascript">
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}
</script>
</head>

<body onLoad="checkCookie()">
</body>
</html>
 

通过JQuery插件实 现cookie操作

你可以在这款插件的主页下载到它:http://plugins.jquery.com/project/Cookie

 

这里是一个示例页面:在 线示例

 

当在页面中引用了jquery文件及该插件文件后,可进行如下操作:

 

设置cookie

设置一个名称为blog,值为css9.net的cookie:

 

$.cookie("blog", "css9.net");
 

设置一个名称为blog,值为css9.net的cookie,同时设置过期时间(expires属性)为7天:

 

$.cookie("blog", "css9.net", { expires: 7 });
 

设置一个名称为blog,值为css9.net的cookie,设置过期时间(expires属性)为7天,同时设置cookie 的path属性 为”/admin”

 

$.cookie("blog", "css9.net", { path: '/admin', expires: 7 });
 

读取Cookie:

读取名称为blog的cookie值:

 

alert( $.cookie("blog") );
 

删除cookie:

 

$.cookie("example", null);
 

我简单看了下插件脚本的内容,实现是非常简单的。为了这样一个功能,要多引用一个文件,增加一个http连接数,感觉有些不值。其实可以把这个插件 里面的功能方法提出来,合并到网站的js文件中,使用时方法是一样的。

 

 

代码:

 

/**
 * 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.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
        }
        // CAUTION: 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.blockUI.js

    Jquery全屏遮掩及加载条插件,使用: &lt;script type="text/javascript" ...&lt;script type="text/javascript" src="js/jquery.cookie.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery.blockUI.js"&gt;&lt;/script&gt;

    cookie设置插件jquery.cookie.min.js

    cookie设置插件jquery.cookie.min.js 文章《javascript设置cookie高级篇可跨域访问》https://blog.csdn.net/cplvfx/article/details/117822956

    jquery 设置cookie、删除cookie、获取cookie

    jquery 设置cookie、删除cookie、获取cookie

    jquery操作cookie所需js包cookiejs-cookie

    jquery操作cookie所需js包cookiejs-cookie

    最新jquery操作cookie插件

    Cookie操作是我们在Web开发中经常会用到的功能,以往我们一般是通过javascript实现的。下面这款jQuery插件是专门用来进行cookie操作的,包括cookie的添加、清除、读取。

    jquery.cookie.js

    支持jquery库下调用jquery.cookie.js

    jquery下cookie插件使用

    jQuery Cookie 插件使用及查看cookie 注:在默认情况下,只有设置 cookie 的网页才能读取该 cookie。如果想让一个页面读取另一个页面设 置的cookie,必须设置 cookie 的路径。cookie 的路径用于设置能够读取 cookie ...

    jquery-cookie(Jq取cookie必备).rar

    该包可以用于jq直接取值cookie,需要的可以直接下载,具体的使用方法在压缩包中有个“介绍.txt”,下载后直接可以使用

    jquery网页换肤

    &lt;script language="javascript" src="Scripts/jquery.cookie.js" type="text/javascript"&gt;&lt;/script&gt; &lt;!--这是Scripts文件夹中的核心代码ChangeSkin.js--&gt; &lt;script language="javascript" src="Scripts/ChangeSkin.js...

    jquery-cookie:jQuery Cookie 插件

    jquery-cookie jquery cookie 插件安装使用安装: $ component install virtru-components/jquery-cookie应用程序接口执照麻省理工学院

    jquery-cookie:一个处理cookie的jquery插件

    jquery.cookie 使用介绍一个轻量级的cookie 插件,可以读取、写入、删除 cookie。jquery.cookie.js 的配置###第一种首先包含jQuery的库文件,在后面包含 jquery.cookie.js 的库文件。[removed][removed][removed]...

    ihavecookies:jQuery插件,用于显示cookie同意消息(欧盟法规)

    jQuery Cookie同意插件(WIP) 一个显示cookie的轻量级jQuery插件 :cookie: 欧盟法规要求的同意消息。 该插件会在用户首次访问您的网站时显示一条消息,默认情况下会在用户最后一次访问后30天再次显示一条消息。 ...

    浏览器中使用JS操作Cookie详解

    并且在Cookie详解这篇文章中,介绍了如何在服务器端和使用JavaScript创建Cookie,并设置属性。 ​我们知道,Cookie是存储在客户端的,并且现在前后端分离慢慢变得流行起来,因此如何在浏览器上可以使用方便快捷的...

    jquery cookie.js

    一个js文件。引入页面后可使用jquery操作cookie,方便简单。附有一个记住用户名和密码的例子。

    jquery-cookie:从 https 分叉

    jquery.cookie 一个简单、轻量级的 jQuery 插件,用于读取、写入和删除 cookie。 如果您在查看此内容,则您正在阅读 master 分支的文档。 构建状态矩阵 安装 在 jQuery 库之后包含脚本(除非您以其他方式打包脚本...

    详解jQuery的Cookie插件

    一、jQuery.Cookie.js插件是一个轻量级的Cookie管理插件。  特别提醒,今日发现一个特别的错误,google浏览器提示:has no method $.cookie。火狐浏览器提示:$.cookie is not a function;调试了半天,终于找到原因...

    jQuery权威指南-源代码

    其次详细讲解了jQuery的各种选择器、jQuery操作DOM的方法、jQuery中的事件与应用、jQuery中的动画和特效、Ajax在jQuery中的应用,以及各种常用的jQuery插件的使用方法和技巧,所有这些知识点都配有完整的示例(包括...

    利用js(jquery)操作Cookie的方法说明

    Cookie操作是我们在Web开发中经常会用到的功能,以往我们一般是通过javascript实现的。下面这款jquery插件是专门用来进行cookie操作 的,包括cookie的添加、清除、读取……你可以在这款插件的主页下载到它:...

    最新Color Admin1.9 - bootstrap3响应后台模板+前端网页模板

    jQuery Cookie: https://github.com/carhartl/jquery-cookie Switchery: http://abpetkov.github.io/switchery/ Powerange: http://abpetkov.github.io/powerange/ X-Editable: ...

    jquery插件推荐 jquery.cookie

    通过原生的JavaScript实现处理cookies是一项头疼的工作,并且jQuery本身也不具备解决处理cookies的函数, 但是这个极其小(压缩后解决500字节左右)的jquery插件可以用来处理cookies的读写和删除。 兼容性 IE6+、...

Global site tag (gtag.js) - Google Analytics