如何使用javascript管理多个cookie用于相同的URL

时间:2016-07-25 09:50:04

标签: javascript php jquery

我是jquery的新手,我想在jquery的页面中管理几个cookie。

setcookie($cookie_name,$cookie_value,$time,"/");
像这个我想要的PHP功能

2 个答案:

答案 0 :(得分:1)

一个让这个变得非常简单的小型库是js-cookieavailable here

设置有效期为30天的Cookie:

var options = {expires: 30, path:'/'}
Cookies.set("cookie_name", cookie_value, options);

阅读Cookie的值

 var cookie_value = Cookies.get("cookie_name");

获取所有可用的cookie

var cookies = Cookies.get();

删除Cookie:

Cookies.remove("cookie_name", {path:'/'});

答案 1 :(得分:0)

你可以用这个

    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    function eraseCookie(name) {
        createCookie(name, "", -1);
    }

createCookie("mycookie_"+id,cookievalue,7);