网站首页技术博客

JS 存储和获取cookie​

洞天水月2021-03-12 14:33:301439人次阅读
摘要之前做cookie都是用php,最近接到一个项目需要在静态页面中添加cookie,就想到了js,度娘上查了点资料,找了下w3c的文档,轻松解决这个问题

之前做cookie都是用php,最近接到一个项目需要在静态页面中添加cookie,就想到了js,度娘上查了点资料,找了下w3c的文档,轻松解决这个问题

存储cookie的函数

function setCookie(c_name, value, expiredays) {
			var exdate = new Date();
			exdate.setDate(exdate.getDate() + expiredays);
			document.cookie=c_name+"="+escape(value)+((expiredays == null)?"":";expires="+exdate.toGMTString());
		}

三个参数分别代表存储的变量名称,变量值,cookie存活周期(整数类型,单位天)

获取cookie的函数

function getCookie(c_name) { 
			if (document.cookie.length>0) {
				c_start=document.cookie.indexOf(c_name + "=")  
				if (c_start!=-1) {    
					c_start=c_start + c_name.length+1;  
					c_end=document.cookie.indexOf(";",c_start) ;  
					if (c_end==-1) c_end=document.cookie.length;    
					return (document.cookie.substring(c_start,c_end));  
				}
			} 
			return "";
		}

注:通过物理路径即D:/wwwroot/index.html这样的路径是不能够存储和读取cookie的,需要通过域名或ip或虚拟目录才可以正常存储并读取cookie


文章评论