在cookie中存储信息

Storing information in cookies

本文关键字:信息 存储 cookie      更新时间:2023-09-26

谁知道在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);
    }
}

cookie插件

您可以使用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);
        } 
    }   
}