1,用JS设定cookie方法是:document.cookie="xxx".
2,注意这样一次只能设定一个cookie变量值,如document.cookie="a=1;b=2;expires=xx";这样无法正常写入b的值,正确的写入方法应该是
document.cookie="a=1";
document.cookie="b=2";
一般设定cookie都专门写一个函数调用。如setCookie(name,value,expires).
3,读取cookie值时用分号“;”分割,如documen.cookie.split(";").因为cookie是用分号来分隔变量的。
测试代码:<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title></title>
</head>
<body>
<div id="a"></div>
<script type="text/javascript">
function setCookie(name,value){
var cookieValue=name+"="+value;
var expires=new Date(2006,07,01).toGMTString();
cookieValue=cookieValue+";expires="+expires;
document.cookie=cookieValue;
return "";
}
function getCookie(name){
var search=name+"=";
if(document.cookie.length>0){
var offset=document.cookie.indexOf(search);
offset+=search.length;
end=document.cookie.indexOf(";",offset);
if(end==-1)
end=document.cookie.length;
return document.cookie.substring(offset,end);
}else
return "";
}
function getAllCookie(){
var allCookie=document.cookie;
var cookie=new Array();
if(allCookie.length>0){
var cookie=allCookie.split(";");
for(var i=0;i<cookie.length;i++)
alert(cookie[i]);
}
}
setCookie("a","111");
setCookie("b","222");
setCookie("c","456");
alert("a="+getCookie("a"));
alert("b="+getCookie("b"));
alert("c="+getCookie("c"));
alert("Now Call getAllCookie()");
getAllCookie();
</script>
</body>
</html>