javascript操作cookie的方法

第一步:

1.servlet或者jsp设置的cookie是可以用javascript来读取的,但是设置就会出现重名的现象.

2.最近项目用到一个可有可无的功能,就是每24小时弹出一个消息框,告诉用户分享资源,这样的功能用cookie是再合适不过了.

第二步:

1.以下的代码是javascript实现cookie用到的基础方法:

function GetCookieVal(offset)
//获得Cookie解码后的值
{
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)
	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function SetCookie(name, value)
//设定Cookie值
{
	var expdate = new Date();
	var argv = SetCookie.arguments;
	var argc = SetCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	expdate.setTime(expdate.getTime() + 1000*60*60*24 );//设置cookie在客户端的存活时间
	document.cookie = name + "=" + escape (value)+"; expires="+ expdate.toGMTString() + ";path=/";//设置根路径和存活的时间
}
function DelCookie(name)
//删除Cookie
{
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = GetCookie (name);
	document.cookie = name + "=" + cval + "; expires="+ exp.toGMTString();
}
function GetCookie(name)
//获得Cookie的原始值
{
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen)
	{
	var j = i + alen;
	if (document.cookie.substring(i, j) == arg)
	return GetCookieVal (j);
	i = document.cookie.indexOf(" ", i) + 1;
	if (i == 0) break;
	}
	return null;
}
//公共处理发表feed
function getFeedStatus(num){
	var cookieName = "FEED_COOKIE_STATE";
	var result = false;
	if( cookieName==null || cookieName=="" ){
		return result;
	}
	var cookieValue = GetCookie(cookieName);
	if(cookieValue==null){
		return result;
	}
	if( num>=cookieValue.length || num<0 ){
		return result;
	}
	if(cookieValue.charAt(num)!=null && cookieValue.charAt(num)=="0"){
		cookieValue = cookieValue.substring(0,num) + "1" + cookieValue.substring(num+1);
		SetCookie(cookieName,cookieValue);
		result = true;
	}
	return result;
}

相关推荐