如何在jquery cookie中存储数组?

muk*_*van 22 arrays cookies jquery

我需要在jQuery cookie中存储一个数组,任何人都可以帮助我吗?

alm*_*ori 57

仍然不完全确定你需要什么,但我希望这会有所帮助.这是一个允许您访问任何页面上的项目的示例,它只是一个示例!它使用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;
    }
  }
}  
Run Code Online (Sandbox Code Playgroud)

因此,在任何页面上,您都可以获得这样的项目.

var list = new cookieList("MyItems"); // all items in the array.
Run Code Online (Sandbox Code Playgroud)

将项添加到cookieList

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

将所有项目作为数组

alert(list.items());
Run Code Online (Sandbox Code Playgroud)

清除物品

list.clear();
Run Code Online (Sandbox Code Playgroud)

您可以非常轻松地添加推送和弹出等其他内容.再希望这会有所帮助.

编辑 如果您遇到IE问题,请参阅bravos答案


alm*_*ori 11

在这里下载jQuery cookie插件:http://plugins.jquery.com/project/Cookie

使用jQuery设置cookie就像这样简单,我们创建一个名为"example"的cookie,其值为["foo1","foo2"]

$.cookie("example", ["foo1", "foo2"]);
Run Code Online (Sandbox Code Playgroud)

使用jQuery获取cookie的价值也很容易.以下将在对话框窗口中显示"example"cookie的值

alert( $.cookie("example") );
Run Code Online (Sandbox Code Playgroud)