Javascript操作Cookie的脚本 — CookieHelper

本文介绍了一个JavaScript实现的Cookie管理工具,包括创建、读取、删除Cookie等功能,并提供了使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

var HttpCookie = function(name, value, expires, path, domain) {

if (name)

this.Name = name;

if (value)

this.Value = value;

if (expires)

this.Expires = expires;

if (path)

this.Path = path;

if (domain)

this.Domain = domain;

};

HttpCookie.prototype = {

Name : '',

Value : '',

Expires : '',

Path : '/',

Domain : '',

toCookie : function() {

var NewCookie = this.Name + '=' + this.Value;

if (this.Expires)

NewCookie += (';expires=' + this.Expires);

if (this.Path)

NewCookie += (';path=' + this.Path);

if (this.Domain)

NewCookie += (';domain=' + this.Domain);

return NewCookie;

}

}

var CookieHelper = function() {

};

CookieHelper.ConvertToUTCString = function(hourNumber) {

if (!hourNumber || hourNumber == 0)

return null;

var Timestamp = (new Date().getTime() + (hourNumber * 1000 * 60 * 60));

return new Date(Timestamp).toUTCString();

};

CookieHelper.Set = function(cookieName, cookieValue, expireHour, path, domain) {

var HC = new HttpCookie(cookieName, escape(cookieValue), CookieHelper

.ConvertToUTCString(expireHour), path, domain);

document.cookie = HC.toCookie();

};

CookieHelper.Get = function(cookieName) {

var regex = new RegExp(("(^| )" + cookieName + "=([^;]*)(;|$)"));

var Matchs = document.cookie.match(regex);

if (Matchs)

return (Matchs[2]);

return null;

};

CookieHelper.Delete = function(cookieName, path, domain) {

if (!CookieHelper.Get(cookieName))

return;

var HC = new HttpCookie(cookieName, null, CookieHelper

.ConvertToUTCString(-100));

document.cookie = HC.toCookie();

};

使用示例:

添加COOKIE,设置COOKIE的值:

CookieHelper.Set(cookieName, cookieValue, expireHour, path, domain);

示例:

CookieHelper.Set('cookie_name', 'cookie_value', 1);

//删除COOKIE CookieHelper.Delete('cookie_name');

//获取COOKIE的值 CookieHelper.Get('cookie_name');

原文出处:http://www.zu14.cn/2010/08/16/javascript-cookie-helper/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值