Home  >  Article  >  Web Front-end  >  Javascript读取cookie函数代码_javascript技巧

Javascript读取cookie函数代码_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:18:241002browse

用法:
一、设置cookie

复制代码 代码如下:

var cookie = new JSCookie();
// 普通设置
cookie .SetCookie("key1","val1");
// 过期时间为一年
var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie .SetCookie("key2","val2",expire_time);
// 设置域及路径,带过期时间
cookie .SetCookie("key3","val3",expire_time,".cnblogs.com","/");
// 设置带子键的cookie,子键分别是k1,k2,k3
cookie .SetCookie("key4","k1=1&k2=2&k3=3");


二、读取cookie
复制代码 代码如下:

// 简单获取
cookie .GetCookie("key1");
cookie .GetCookie("key2");
cookie .GetCookie("key3");
cookie .GetCookie("key4");
// 获取key4的子键k1值
cookie .GetChild("key4","k1");


三、删除
复制代码 代码如下:

cookie .Expire("key1");
cookie .Expire("key2");
cookie .Expire("key3");
cookie .Expire("key4");


示例:
复制代码 代码如下:



用正则的方法读取cookie值
由于asp的cookie是经过url编码的,所以读之前要unescape一下。

下面是我用正则的方法取cookie,包括单值和多值:
复制代码 代码如下:

/**************************************************
参数说明:
sMainName Cookie名
sSubName Cookie子键名,留空表示单值Cookie
**************************************************/
function GetCookie(sMainName, sSubName)
{
var re = new RegExp((sSubName ? sMainName + "=(?:.*?&)*?" + sSubName + "=([^&;$]*)" : sMainName + "=([^;$]*)"),"i");
return re.test(unescape(document.cookie)) ? RegExp["$1"] : "";
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn