分享

Javascript操作Cookie的脚本

 posondlq 2011-06-16

这是一个Javascript操作Cookie的功能封装,对于制作购物车之类的,还是比较实用的,功能包括 添加COOKIE,删除COOKIE,获取COOKIE的值

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 unescape(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');

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多