2009-12-24 96 views
20

我需要將數組存儲在jQuery cookie中,請幫助我嗎?如何在jQuery Cookie中存儲數組?

+0

什麼是「jQuery cookie」?你指的是其中一個插件嗎? – 2009-12-24 19:28:07

+0

它是一個jQuery插件。我想動態地將數組定位到cookie。 – mukamaivan 2009-12-24 20:06:23

+1

http://stackoverflow.com/questions/4225030/jquery-save-json-data-object-in-cookie – Andrei 2011-12-25 16:17:39

回答

55

仍然不完全確定您需要什麼,但我希望這會有所幫助。 這是一個示例,它允許您訪問任何頁面上的項目,它只是一個示例! 它使用cookieName在頁面中標識它。

//This is not production quality, its just demo code. 
var cookieList = function(cookieName) { 
//When the cookie is saved the items will be a comma seperated string 
//So we will split the cookie by comma to get the original array 
var cookie = $.cookie(cookieName); 
//Load the items or a new array if null. 
var items = cookie ? cookie.split(/,/) : new Array(); 

//Return a object that we can use to access the array. 
//while hiding direct access to the declared items array 
//this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html 
return { 
    "add": function(val) { 
     //Add to the items. 
     items.push(val); 
     //Save the items to a cookie. 
     //EDIT: Modified from linked answer by Nick see 
     //  http://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie 
     $.cookie(cookieName, items.join(',')); 
    }, 
    "remove": function (val) { 
     //EDIT: Thx to Assef and luke for remove. 
     indx = items.indexOf(val); 
     if(indx!=-1) items.splice(indx, 1); 
     $.cookie(cookieName, items.join(','));  }, 
    "clear": function() { 
     items = null; 
     //clear the cookie. 
     $.cookie(cookieName, null); 
    }, 
    "items": function() { 
     //Get all the items. 
     return items; 
    } 
    } 
} 

所以在任何頁面上你都可以得到這樣的物品。

var list = new cookieList("MyItems"); // all items in the array. 

添加條目至cookieList

list.add("foo"); 
//Note this value cannot have a comma "," as this will spilt into 
//two seperate values when you declare the cookieList. 

獲取的所有項目作爲一個數組

alert(list.items()); 

清除項目

list.clear(); 

您可以添加其他的東西像推和流行相當甲硅烷。 再次希望這有助於。

編輯 見BRAVOS答案,如果您有與IE

+0

Thanx Ori,我已經完成了功能,它的工作... – mukamaivan 2009-12-27 12:33:48

+0

嗨 - 感謝您的代碼。我只是試了一下,除非我調用remove函數'list.remove(「foo」)''它不會將它從cookie中移除,否則它會很好用。清除和添加工作正常,有什麼與刪除? – Redwall 2013-09-17 06:34:06

+0

我基於我的cookie對象來跟蹤評論upvotes和downvotes爲客人。我瞭解了關閉!感謝almog.ori! – 2013-11-08 18:15:51

10

下載jQuery的cookie的插件在這裏:http://plugins.jquery.com/project/Cookie

設置使用jQuery一個cookie是如此簡單,我們正在創建一個名爲「榜樣」的cookie的值「foo1」,「foo2的」]

$.cookie("example", ["foo1", "foo2"]); 

使用jQuery獲取cookie的值也非常簡單。以下將顯示對話窗口中的「示例」cookie的值

alert($.cookie("example")); 
+0

Thanx Ori,它的工作原理。但後來我的實際問題是在數組cookie的onclick值。在多個頁面上完成所有事情之後,我可以將cookie元素的每個數組元素附加到無序列表(ul),並能夠彈出客戶端感覺像的任何索引。 請多幫忙。 – mukamaivan 2009-12-24 20:13:40

+0

不確定你的意思,但是id是從一個單擊時調用的函數開始的,它保存了「選擇」(或者你需要的任何東西),這可以放在一個單獨的js文件中,不同的頁面使用腳本引用標記與網址。 – 2009-12-24 20:32:39

+0

好我的js是一個外部文件。 我希望這個示例代碼給你一個線索,我想要什麼。 $(函數(){ \t \t/**這是我傾向於做*/ \t \t $ .cookie( 'cookieItem',msg.txt,{到期:1}); \t \t myCookie_arr。推($餅乾( 'cookieItem')); //在我的餅乾陣列 \t \t .. \t $(窗口).load(函數(){ \t \t .. \t \t警報的末尾添加元素(myCookie_arr); \t \t for(var i = 0; i mukamaivan 2009-12-24 21:37:32

0

問題你可以存儲爲cookie之前序列化數組,然後讀取時反序列化。即與json?

1

我加入了"remove"行動,誰想要使用它 - val是該指數在其開始改變數組:

"remove": function (val) { 
     items.splice(val, 1); 
     $.cookie(cookieName, items.join(',')); 
    } 
+0

cool nice addition :) – 2012-01-18 20:02:41

1

只是一個小的替代"remove"功能:

"removeItem": function (val) { 
     indx = items.indexOf(val); 
     if(indx!=-1) items.splice(indx, 1); 
     $.cookie(cookieName, items.join(',')); 
    } 

其中val是數組e中項目的值。G:

>>> list.add("foo1"); 
    >>> list.add("foo2"); 
    >>> list.add("foo3"); 
    >>> list.items(); 

    ["foo1", "foo2", "foo3"]; 

    >>> list.removeItem("foo2"); 
    >>> list.items(); 

    ["foo1", "foo3"]; 
3

看看我的實現(作爲一個jQuery插件):

(function ($) { 
    $.fn.extend({ 
     cookieList: function (cookieName) { 
      var cookie = $.cookie(cookieName); 

      var items = cookie ? eval("([" + cookie + "])") : []; 

      return { 
       add: function (val) { 
        var index = items.indexOf(val); 

        // Note: Add only unique values. 
        if (index == -1) { 
         items.push(val); 
         $.cookie(cookieName, items.join(','), { expires: 365, path: '/' }); 
        } 
       }, 
       remove: function (val) { 
        var index = items.indexOf(val); 

        if (index != -1) { 
         items.splice(index, 1); 
         $.cookie(cookieName, items.join(','), { expires: 365, path: '/' }); 
        } 
       }, 
       indexOf: function (val) { 
        return items.indexOf(val); 
       }, 
       clear: function() { 
        items = null; 
        $.cookie(cookieName, null, { expires: 365, path: '/' }); 
       }, 
       items: function() { 
        return items; 
       }, 
       length: function() { 
        return items.length; 
       }, 
       join: function (separator) { 
        return items.join(separator); 
       } 
      }; 
     } 
    }); 
})(jQuery); 

用法:

var cookieList = $.fn.cookieList("cookieName"); 
    cookieList.add(1); 
    cookieList.add(2); 
    cookieList.remove(1); 
    var index = cookieList.indexOf(2); 
    var length = cookieList.length(); 
+0

實際上,如果數組將同時通過頁面的多個插件/控件訪問,那麼在任何活動(不要將其存儲到項目變量之前)重新讀取cookie會更好。 – 2012-04-13 14:32:01

2

此實現提供了頁面上的多個控件獨立訪問:

(function ($) { 
    $.fn.extend({ 
     cookieList: function (cookieName) { 

      return { 
       add: function (val) { 
        var items = this.items(); 

        var index = items.indexOf(val); 

        // Note: Add only unique values. 
        if (index == -1) { 
         items.push(val); 
         $.cookie(cookieName, items.join(','), { expires: 365, path: '/' }); 
        } 
       }, 
       remove: function (val) { 
        var items = this.items(); 

        var index = items.indexOf(val); 

        if (index != -1) { 
         items.splice(index, 1); 
         $.cookie(cookieName, items.join(','), { expires: 365, path: '/' }); 
        } 
       }, 
       indexOf: function (val) { 
        return this.items().indexOf(val); 
       }, 
       clear: function() { 
        $.cookie(cookieName, null, { expires: 365, path: '/' }); 
       }, 
       items: function() { 
        var cookie = $.cookie(cookieName); 

        return cookie ? eval("([" + cookie + "])") : []; ; 
       }, 
       length: function() { 
        return this.items().length; 
       }, 
       join: function (separator) { 
        return this.items().join(separator); 
       } 
      }; 
     } 
    }); 
})(jQuery); 
+1

爲什麼2個答案?如果您不滿意/必須更新您的答案,請使用「編輯」功能。 – BlackBear 2012-04-14 11:17:52

+0

+1喜歡jquery插件 – 2012-05-26 16:48:27

+0

第一個實現將工作得更快一點,而第二個稍慢一些,但在這種情況下,該數組可以通過單個頁面上的多個控件訪問,甚至可以從不同的選項卡訪問,數組將始終是實際的。 – 2012-05-29 08:51:09

3

我有錯誤,當我嘗試使用almog.ori的腳本在IE 8

//This is not production quality, its just demo code. 
    var cookieList = function(cookieName) { 
    //When the cookie is saved the items will be a comma seperated string 
    //So we will split the cookie by comma to get the original array 
    var cookie = $.cookie(cookieName); 
    //Load the items or a new array if null. 
    var items = cookie ? cookie.split(/,/) : new Array(); 

    //Return a object that we can use to access the array. 
    //while hiding direct access to the declared items array 
    //this is called closures see http://www.jibbering.com/faq/faq_notes/closures.html 
    return { 
     "add": function(val) { 
      //Add to the items. 
      items.push(val); 
      //Save the items to a cookie. 
      //EDIT: Modified from linked answer by Nick see 
      //  https://stackoverflow.com/questions/3387251/how-to-store-array-in-jquery-cookie 
      $.cookie(cookieName, items.join(',')); 
     }, 
     "remove": function (val) { 
      //EDIT: Thx to Assef and luke for remove. 
      indx = items.indexOf(val); 
      if(indx!=-1) items.splice(indx, 1); 
      $.cookie(cookieName, items.join(','));  }, 
     "clear": function() { 
      items = null; 
      //clear the cookie. 
      $.cookie(cookieName, null); 
     }, 
     "items": function() { 
      //Get all the items. 
      return items; 
     } 
     } 

} 

幾個小時挖錯誤後,我才意識到是在的indexOf

"remove": function (val) { 
       //EDIT: Thx to Assef and luke for remove. 
       indx = items.indexOf(val); 
       if(indx!=-1) items.splice(indx, 1); 
       $.cookie(cookieName, items.join(','));  }, 

不支持IE 8

,所以我在另一個代碼庫從這裏添加How to fix Array indexOf() in JavaScript for Internet Explorer browsers

它的工作原理,

"remove": function (val) { 
    //EDIT: Thx to Assef and luke for remove. 
    /** indexOf not support in IE, and I add the below code **/ 
    if (!Array.prototype.indexOf) { 
     Array.prototype.indexOf = function(obj, start) { 
      for (var i = (start || 0), j = this.length; i < j; i++) { 
       if (this[i] === obj) { return i; } 
      } 
      return -1; 
     } 
    } 
    var indx = items.indexOf(val); 
    if(indx!=-1) items.splice(indx, 1); 
    //if(indx!=-1) alert('lol'); 
    $.cookie(cookieName, items.join(',')); 
}, 

只是爲了防止任何人發現該腳本不在IE 8中工作,這可能會有所幫助。

+0

+1不錯的加法:) – 2012-06-05 11:03:22

+0

刪除方法也填充本地數組對象是你不希望從刪除方法。意想不到的副作用。 – oyvindn 2012-08-17 10:33:01

2

我稍微調整了示例以使用JSON編碼和secureJSON解碼,使其更加健壯和節省。

這取決於https://code.google.com/p/jquery-json/

/* 
* Combined with: 
* http://www.terminally-incoherent.com/blog/2008/11/25/serializing-javascript-objects-into-cookies/ 
* With: 
* https://code.google.com/p/jquery-json/ 
* 
*/ 
(function ($) { 
    $.fn.extend({ 
     cookieList: function (cookieName, expireTime) { 

      var cookie = $.cookie(cookieName);    
      var items = cookie ? $.secureEvalJSON(cookie) : []; 

      return { 
       add: function (val) { 
        var index = items.indexOf(val); 
        // Note: Add only unique values. 
        if (index == -1) { 
         items.push(val); 
         $.cookie(cookieName, $.toJSON(items), { expires: expireTime, path: '/' }); 
        } 
       }, 
       remove: function (val) { 
        var index = items.indexOf(val); 

        if (index != -1) { 
         items.splice(index, 1); 
         $.cookie(cookieName, $.toJSON(items), { expires: expireTime, path: '/' }); 
        } 
       }, 
       indexOf: function (val) { 
        return items.indexOf(val); 
       }, 
       clear: function() { 
        items = null; 
        $.cookie(cookieName, null, { expires: expireTime, path: '/' }); 
       }, 
       items: function() { 
        return items; 
       }, 
       length: function() { 
        return items.length; 
       }, 
       join: function (separator) { 
        return items.join(separator); 
       } 
      }; 
     } 
    }); 
})(jQuery); 
+0

優秀。在這個頁面上使用eval(「([」+ cookie +「])」)的代碼片段無法處理字符串(我猜它們只能用於數字)。 – 2014-02-06 15:41:35

3

我不知道這是否會幫助別人,但我還需要來檢查,如果已經存在的項目,所以我不重新添加它的功能。

我用同樣的刪除功能,並改變它是包含功能:

"contain": function (val) { 
//Check if an item is there. 
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) { 
     for (var i = (start || 0), j = this.length; i < j; i++) { 
      if (this[i] === obj) { return i; } 
     } 
     return -1; 
    }; 
} 
var indx = items.indexOf(val); 
if(indx>-1){ 
    return true; 
}else{ 
    return false; 
} 
}, 

出於某種原因上面的代碼並不總是工作。所以這裏是新的工作:

"contain": function (val) { 
//Check if an item is there. 
if (!Array.prototype.indexOf) { 
    Array.prototype.indexOf = function(obj, start) { 
     for (var i = (start || 0), j = this.length; i < j; i++) { 
      if (this[i] === obj) { return i; } 
     } 
     return -1; 
    }; 
} 
var indx = items.join(',').indexOf(val); 
if(indx > -1){ 
    return true; 
}else{ 
    return false; 
} 
}, 
2

好的一段代碼爲我目前正在做的,但發現了一個錯誤。我正在保存一個整數列表(ID)的cookie。但是,當第一次讀取cookie時,它會將字符串轉換爲字符串。我以前保存(int)1,並且稍後當在頁面上檢索cookie時,重新加載將它指定爲「1」。因此,當我嘗試從列表中刪除(int)1時,它不會索引匹配。

我應用的修正是在添加或索引項目之前將「val」表達式更改爲val.toString()。因此項目是一個字符串數組。

"add": function(val) { 
    //Add to the items. 
    items.push(val.toString()); 
    //Save the items to a cookie. 
    $.cookie(cookieName, items.join(',')); 
}, 

"remove": function (val) { 
    //EDIT: Thx to Assef and luke for remove. 
    if (!Array.prototype.indexOf) { 
     Array.prototype.indexOf = function(obj, start) { 
      for (var i = (start || 0), j = this.length; i < j; i++) { 
       if (this[i] === obj) { return i; } 
      } 
      return -1; 
     }; 
    } 

    var indx = items.indexOf(val.toString()); 
    if(indx!=-1) items.splice(indx, 1); 
    //Save the items to a cookie. 
    $.cookie(cookieName, items.join(',')); 
}, 
2

這是如何使用json和jquery在cookie中存儲和檢索數組。

//Array  
var employees = [ 
       {"firstName" : "Matt", "lastName" : "Hendi"}, 
       {"firstName" : "Tim", "lastName" : "Rowel"} 
]; 

var jsonEmployees = JSON.stringify(employees);//converting array into json string 
$.cookie("employees", jsonEmployees);//storing it in a cookie 

var empString = $.cookie("employees");//retrieving data from cookie 
var empArr = $.parseJSON(empString);//converting "empString" to an array. 
0

這裏是JSON實現與餅乾,用於存儲陣列更好的方式工作。從我的最終測試。

$.fn.extend({ 
    cookieList: function (cookieName) { 
     var cookie = $.cookie(cookieName); 

     var storedAry = (cookie == null) ? [] : jQuery.parseJSON(cookie); 


     return { 
      add: function (val) { 

       var is_Arr = $.isArray(storedAry); 
       //console.log(storedAry); 


       if($.inArray(val, storedAry) === -1){ 
       storedAry.push(val); 
       //console.log('inside'); 
       } 

       $.cookie(cookieName, JSON.stringify(storedAry), { expires : 1 , path : '/'}); 
       /*var index = storedAry.indexOf(val); 
       if (index == -1) { 
        storedAry.push(val); 
        $.cookie(cookieName, storedAry.join(','), { expires: 1, path: '/' }); 
       }*/ 
      }, 
      remove: function (val) { 

       storedAry = $.grep(storedAry, function(value) { 
       return value != val; 
       }); 
       //console.log('Removed '+storedAry); 

       $.cookie(cookieName, JSON.stringify(storedAry), { expires : 1 , path : '/'}); 
       /*var index = storedAry.indexOf(val); 
       if (index != -1){ 
        storedAry.splice(index, 1); 
        $.cookie(cookieName, storedAry.join(','), { expires: 1, path: '/' }); 
       }*/ 
      } 
      clear: function() { 
       storedAry = null; 
       $.cookie(cookieName, null, { expires: 1, path: '/' }); 
      } 
     }; 
    } 

});

相關問題