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]);
}
}
//方法三
有坑:
WMSEMPID=01011540; EMPID=00012152;cookiename是EMPID取的是第一个cookie。
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;
}