一般关于js读取cookie方法有很多,下面的实例函数主要是利用split函数来分切,和document.cookie获取所有cookie再利用for遍历所有数组,判断如果cookie名相同,那么这个cookie 就是我们要找的。
方法一
代码如下:
var acookie = document.cookie.split("; ");
function getck(sname) {//获取单个cookies
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) {//获取指定名称的cookie的值
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;
}