2011-10-20 192 views
0

有誰知道在cookie中存儲信息的強大類嗎?在cookies中存儲信息

我只想寫類似:

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是餅乾插件

回答

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); 
     } 
    } 
}