js/jquery操作cookie[原+转]

2011/1/30更新:

以前转了下面的内容,其实我在自己的项目里,用的基本上是这两个方法

//取cookie值
function getCookie(name){
		var arr = document.cookie.match(new RegExp("(^|;\\s*)"+name+"=([^;]*)(;|$)"));//当时这个正则测了我很久,应该没问题了,下面有解释
		if(arr != null) return unescape(decodeURI(arr[2])); return "";
} 
//设置cookie
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.toUTCString());
}

getCookie里的正则说明:

比如我们要找member_id这个cookie,那么name就是member_id,上面的正则判断了三种情况:

以member_id开头、member_id在cookie字串中间,member_id在字串末尾。

所以我们要匹配的是name+"=([^;]*),并且把值放在分组里面,这一段可以从name开始匹配

匹配到什么时候结束呢 (;|$),意思是匹配到名字后的第一个分号,假如是位置是最后一段,那么就没有分号,可是已经是结尾($)了

从什么时候开始?同样,(^|;\s*),它要么是开头,要么前面就跟了分号和空格,以隔开前一个属性,这就是这个正则的原理了

一段示例cookie:

"__utma=159719458.1137661975.1293897187.1295113964.1295271343.12; __utmz=159719458.1293897187.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); member_mail=*****%40qq.com; member_nickname=%E5%85%9C%E5%85%9C%E6%B2%A1%E9%92%B1; group_id=0; join_time=1293696797; sitemsg=true; member_id=37; PHPSESSID=lb2ecoespc8asm1ht0stqb43b7"

用上面的正则,得到如下数组:

[

   "; member_id=37;",

   "; ",

   "37",

  ";"

]

第一个元素是最大匹配,然后依次是各个括号里面的,这样,除去最大匹配,第一个括号,我们要的自然是第二个括号里的值了


=======以下是别人的,

全文转载,备份,原文见:http://www.cnblogs.com/qiantuwuliang/archive/2009/07/19/1526663.html

jQuery cookie是个很好的cookie插件,大概的使用方法如下
example $.cookie(’name’, ‘value’);
设置cookie的值,把name变量的值设为value
example $.cookie(’name’, ‘value’, {expires: 7, path: ‘/’, domain: ‘jquery.com’, secure: true});
新建一个cookie 包括有效期 路径 域名等
example $.cookie(’name’, ‘value’);
新建cookie
example $.cookie(’name’, null);
删除一个cookie

var account= $.cookie('name');
取一个cookie(name)值给myvar

代码如下

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
        }
        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;
    }
};

然后看了下Discuz!中对cookie的操作方法
如下,发现少了个遍历用;分割的数组的处理

function getcookie(name) {
var cookie_start = document.cookie.indexOf(name);
var cookie_end = document.cookie.indexOf(";", cookie_start);
return cookie_start == -1 ? '' : unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end : document.cookie.length)));
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
var expires = new Date();
expires.setTime(expires.getTime() + seconds);
document.cookie = escape(cookieName) + '=' + escape(cookieValue)
+ (expires ? '; expires=' + expires.toGMTString() : '')
+ (path ? '; path=' + path : '/')
+ (domain ? '; domain=' + domain : '')
+ (secure ? '; secure' : '');
}
原文地址:https://www.cnblogs.com/walkerwang/p/1904684.html