guolz

JS提供了方便的设置cookie的办法,但是不像PHP那般用一个$_COOKIE函数就可以直接获取,JS需要对cookie的键值对进行操作,以下是汇总的四中读取cookie的方法

//方法一
var acookie = document.cookie.split("; ");
function getcookie(sname){
	for (var i = 0; i < acookie.length; i++) {
		var arr = acookie[i].split("=");
		if (sname == arr[0]) {
			if (arr.length > 1)
				return unescape(arr[1]);
			else
				return "";
		}
	}
	return "";
}
//方法二
function getcookie(objname){
	var arrstr = document.cookie.split("; ");
	for (var i = 0; i < arrstr.length; i++){
		var temp = arrstr[i].split("=");
		if (temp[0] == objname) return unescape(temp[1]);
	}
}
//方法三
function getcookie(cookiename){
	var cookiestring = document.cookie;
	var start = cookiestring.indexof(cookiename + \'= \');
	if (start == -1)
		return null;
	start += cookiename.length + 1;
	var end = cookiestring.indexof("; ", start);
	if (end == -1) return unescape(cookiestring.substring(start));
	return unescape(cookiestring.substring(start, end));
}
//方法四
function readcookie(name){
	var cookievalue = "";
	var search = name + "=";
	if (document.cookie.length > 0){
		offset = document.cookie.indexof(search);
		if (offset != -1){
			offset += search.length;
			end = document.cookie.indexof(";", offset);
			if (end == -1) end = document.cookie.length;
			cookievalue = unescape(document.cookie.substring(offset, end))
		}
	}
	return cookievalue;
}

  

分类:

技术点:

相关文章:

  • 2021-12-18
  • 2021-11-30
  • 2021-11-30
  • 2022-01-30
  • 2021-11-30
  • 2021-08-12
  • 2021-12-19
  • 2021-12-10
猜你喜欢
  • 2022-01-07
  • 2022-02-10
  • 2022-03-01
  • 2022-03-04
  • 2021-08-01
  • 2021-12-22
  • 2021-12-04
相关资源
相似解决方案