【问题标题】:how to store an array in jquery cookie?如何在 jquery cookie 中存储一个数组?
【发布时间】:2010-12-29 21:20:28
【问题描述】:

我需要在 jQuery cookie 中存储一个数组,请有人帮帮我吗?

【问题讨论】:

标签: jquery arrays cookies


【解决方案1】:

仍然不确定您需要什么,但我希望这会有所帮助。 这是一个示例,可让您访问任何页面上的项目,它只是一个示例! 它使用 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();

您可以很容易地添加其他内容,例如推送和弹出。 再次希望这会有所帮助。

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

【讨论】:

  • 嗨 - 感谢您的代码。我刚刚尝试过,效果很好,除非我调用删除函数list.remove("foo") 它不会将其从 cookie 中删除。清除和添加工作正常,删除有什么问题吗?
  • 我基于我的 cookie 对象来跟踪客人的评论赞成和反对。我了解了闭包!谢谢almog.ori!
  • @almog.ori 如何设置永不过期的cookies
  • 试试这个----> $.cookie(cookieName, items.join(','), { expires: 20*365 }); faqs.org/rfcs/rfc2965.html 规范的一部分。
【解决方案2】:

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

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

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

使用 jQuery 获取 cookie 的值也很容易。下面将在对话框窗口中显示“示例”cookie 的值

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

【讨论】:

  • Thanx Ori,它有效。但是我的实际问题是在单击时将值推送到数组 cookie 中。在不止一个页面上完成每件事之后,我可以将 cookie 元素的每个数组元素附加到无序列表 (ul) 中,并能够弹出客户喜欢的任何索引。请提供更多帮助。
  • 不确定你的意思,但 id 以一个函数开始不同的页面使用带有 url 的脚本标签引用。
  • 很好,我的 js 是一个外部文件。我希望这个示例代码能给你一个关于我想要什么的线索。 $(function(){ /**这是我倾向于做的*/ $.cookie('cookieItem', msg.txt, { expires: 1}); myCookie_arr.push($.cookie('cookieItem')) ;// 在我的 cookie 数组的末尾添加元素 .. $(window).load(function() { .. alert(myCookie_arr); for(var i= 0; i
  • 我的变量是:var myCookie; var initial_arr = new Array(); var myCookie_arr = new Array(); var cookieItem;
  • ........ /*******这很有效,但实际上无法实现我想要的***********/ $(' #add_item').click(function(){ initial_arr.push(msg.txt); $.cookie('cookieItem', initial_arr, { expires: 1});//更新新cookie $('#item-list' ).append(msg.txt);//点击附加 }); /******************这是我经常做的事情******************/ $.cookie('cookieItem', msg .txt, { expires: 1});//更新新cookie myCookie_arr.push($.cookie('cookieItem'));//在我的cookie数组末尾添加元素............ .
【解决方案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();

【讨论】:

  • 实际上如果该数组将被页面中的多个插件/控件同时访问,最好在任何活动之前重新读取cookie(不要将其存储到items变量中)。
【解决方案4】:

当我尝试在 IE 8 中使用 almog.ori 的脚本时出错

    //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 中无法运行,这可能会有所帮助。

【讨论】:

  • remove 方法还填充了本机 Array 对象,这是您对 remove 方法所不期望的。意外的副作用。
【解决方案5】:

我不知道这是否会对某人有所帮助,但我还需要检查项目是否已经存在的功能,因此我不再添加它。

我使用了相同的删除功能并将其更改为包含功能:

"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;
}
},

【讨论】:

    【解决方案6】:

    此实现为页面上的多个控件提供独立访问:

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

    【讨论】:

    • 为什么有 2 个答案?如果您不满意/必须更新您的答案,请使用“编辑”功能。
    • 第一个实现会快一点,而第二个会慢一点但是在这种情况下,可以通过单个页面上的多个控件甚至从不同的选项卡和数组将始终是实际的。
    【解决方案7】:

    我稍微调整了示例以使用 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);
    

    【讨论】:

    • 优秀。此页面上使用 eval("([" + cookie + "])") 的代码 sn-ps 无法处理字符串(我猜它们仅适用于数字)。
    【解决方案8】:

    我目前正在做的代码很好,但发现了一个错误。我正在将整数 (ID) 列表保存到 cookie 中。但是,当第一次读取 cookie 时,它​​会转换为字符串。我以前保存(int)1,后来在重新加载页面时检索到cookie时将其指定为“1”。因此,当我尝试从列表中删除 (int) 1 时,它不会索引匹配项。

    我应用的修复是在添加或索引项目之前将“val”表达式更改为 val.toString()。因此 items 是一个字符串数组。

    "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(','));
    },
    

    【讨论】:

      【解决方案9】:

      这是您使用 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. 
      

      【讨论】:

        【解决方案10】:

        我将"remove" 操作添加给任何想要使用它的人 - val 是开始更改数组的索引:

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

        【讨论】:

          【解决方案11】:

          只是"remove" 函数的一个小替代品:

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

          其中val 是数组中某项的值,例如:

             >>> list.add("foo1");
             >>> list.add("foo2");
             >>> list.add("foo3");
             >>> list.items();
          
             ["foo1", "foo2", "foo3"];
          
             >>> list.removeItem("foo2");
             >>> list.items();
          
             ["foo1", "foo3"];
          

          【讨论】:

            【解决方案12】:

            这是使用 cookie 的 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: '/' });
                      }
                  };
              }
            

            });

            【讨论】:

              【解决方案13】:

              您可以在存储为 cookie 之前序列化数组,然后在读取时反序列化。即与json?

              【讨论】:

                猜你喜欢
                • 2012-02-20
                • 1970-01-01
                • 1970-01-01
                • 2023-03-25
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-12-05
                • 2012-07-08
                相关资源
                最近更新 更多