在cookie中存储信息

时间:2011-10-20 09:32:15

标签: javascript cookies

有没有人知道用于在cookie中存储信息的强大类?

我只想写类似的东西:

var cookieStorage = new cookieStorage(100); // 100 - time to store data

var apple = {size:10, color:'red',weight:100};

cookieStorage.set('MyApple',apple);

var restoredApple = cookieStorage.get('MyApple');

我的实施(没有时间存储)

var cookieStorage = {

    set: function (key, value) {

        $.cookie(key, $.toJSON(value));

    },

    get: function (key) {

        var json = $.cookie(key);

        return $.parseJSON(json);
    }

}

Here是Cookie插件

1 个答案:

答案 0 :(得分:0)

您可以使用JSON库来实现此目的。您可以在此处下载JSON:https://github.com/douglascrockford/JSON-js

我为你创建了一个简单的例子。如果你想缩短它,你可以使用JQuery-cookie。

function setCookie(){
    var current = new Array();
    var user = new Object();
    user.FirstName = "Robby";
    user.LastName = "Shaw";
    current.push(user);         //The test value

    var exdate=new Date();
    exdate.setDate(exdate.getDate()+5); //Expire in 5 days
    var cname = "test"; //cookie name
    var value = JSON.stringify(current); //Parse the array

    document.cookie=cname+ "=" +escape(value)+ ";expires="+exdate.toGMTString();
}

function getCookie(){
    var current = new Array();
    if (document.cookie.length>0){
        c_start=document.cookie.indexOf("test=");
        if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1 
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1) c_end=document.cookie.length
        current = JSON.parse(unescape(document.cookie.substring(c_start,c_end)));
        alert(current[0].FirstName+","+current[0].LastName);
        } 
    }   
}