欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

cookie简单封装

程序员文章站 2024-03-20 13:38:34
...

设置cookie

/*
cookieName cookie名字
cookieValue cookie值
cookiePath cookie路径
cookieTime cookie存在时间
*/
function setCookie(cookieName,cookieValue,cookiePath,cookieTime){
	var json = {
		"x" : cookieValue
	}
	cookieValue = JSON.stringify(json);
	var str = cookieName+"="+cookieValue;
	if(cookiePath){
		str += ";path="+cookiePath;
	}
	if(cookieTime){
		var time = new Date();
		time.setMilliseconds(time.getMilliseconds()+cookieTime);
		str += ";expires="+time.toGMTString();
	}
	document.cookie = str;
}

获取cookie

// cookieName cookie的名字
function getCookie(cookieName){
	var str = document.cookie;
	str = decodeURIComponent(str);
	
	var arr = str.split("; ");
	var i = arr.length -1;
	for(var i = arr.length -1;i>=0;i--){
		var ind = arr[i].indexOf("=");
		var a = arr[i].slice(0,ind);
		if( cookieName == a ){
			var str = JSON.parse(arr[i].slice(ind+1));
			console.log(str)
			return str['x'];
		}
	}
	return "";
}

(新人上道)