在Javascript中设置多个cookie

时间:2013-05-30 17:16:45

标签: javascript cookies

我正在尝试在document.cookie中设置多个Cookie,但不幸的是只添加了一个。

我知道'Net上有多个例子用于设置这类cookie,我跟着其中一个。但我仍然无法解决这个问题。 我按照link来设置我的cookie。

我的代码:

   function setCookie(start_time,end_session_time,total_time,flag,count){
     var cookie_string = "start_time="+start_time;;

    if(end_session_time) {
        cookie_string +="; end_session_time="+end_session_time;
    }

    if(total_time){
        cookie_string +="; total_time="+total_time;
    }
    if(flag){
        cookie_string +="; flag="+flag;
    }
    if(count){
        cookie_string +="; count="+count;
    }

    document.cookie =cookie_string ;
    console.log(cookie_string);

    console.log("document.cookie ="+ document.cookie);
}

输出:

cookie_string :: start_time=1369926508266; flag=1; count=1
document.cookie =start_time=1369926508266; 

3 个答案:

答案 0 :(得分:21)

通过document.cookie = "name=value"添加Cookie 要添加多个键,您应该执行多个分配

function setCookie(start_time, end_session_time, total_time, flag, count) {
    document.cookie = "start_time=" + start_time;

    if (end_session_time) {
        document.cookie = "end_session_time=" + end_session_time;
    }
    if (total_time) {
        document.cookie = "total_time=" + total_time;
    }
    if (flag) {
        document.cookie = "flag=" + flag;
    }
    if (count) {
        document.cookie = "count=" + count;
    }

    console.log("document.cookie = " + document.cookie);
}

答案 1 :(得分:18)

Cookie是关键值对(添加了一些可选的附加信息,如到期日期)。要设置多个,您只需设置document.cookie多次。 ;分隔符用于指定其他信息,而不是添加更多不同的Cookie。

答案 2 :(得分:3)

您可以通过示例添加,列出和删除多个Cookie

<!DOCTYPE html>
<html>
<head>
<script>
var n=1;
function addCookie(){
document.cookie=n+"="+n;n++;
}

function ListCookies(){
var result = document.cookie;
document.getElementById("p").innerHTML=result;
}

function removeCookies(){
//document.cookie="";
var result = document.cookie;
var cookieArray = result.split(";");
for(var i=0;i<cookieArray.length;i++){
   var keyValArr = cookieArray[i].split("=");
   document.cookie=keyValArr[0]+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}

</script>

</head>
<body>
<button onclick='addCookie()'>ADD COOKIE</button><br>
<button onclick='ListCookies()'>LIST COOKIES</button>
<button onclick='removeCookies()'>REMOVE COOKIES</button>
<h1>RESULT:</h1>
<p id="p"></p>
</body>
</html>