Подтвердить что ты не робот

Как сохранить массив в jQuery cookie?

Мне нужно сохранить массив в cookie jQuery, кто-нибудь мне поможет?

4b9b3361

Ответ 1

Все еще не совсем уверен, что вам нужно, но я надеюсь, что это поможет. Это образец, который позволит вам получить доступ к элементам на любой странице, это просто образец! Он использует имя файла cookie, чтобы идентифицировать его на всех страницах.

//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.

Добавление элементов в файл cookie

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

Вы можете легко добавлять дополнительные вещи, такие как push и pop. Снова надеемся, что это поможет.

ИЗМЕНИТЬ См. Ответ bravos, если у вас возникли проблемы с IE

Ответ 2

Загрузите плагин jQuery cookie здесь: http://plugins.jquery.com/project/Cookie

Настройка cookie с jQuery так же просто, как это, где мы создаем файл cookie, называемый "example" со значением [ "foo1", "foo2" ]

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

Получение значения cookie также очень просто с jQuery. Ниже показано значение "пример" cookie в диалоговом окне

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

Ответ 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();

Ответ 4

У меня возникла ошибка, когда я пытаюсь использовать almog.ori script в 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.

и поэтому я добавлю в другую базу кода здесь Как исправить Array indexOf() в JavaScript для браузеров Internet Explorer

он работает,

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

на всякий случай, если script не работает в IE 8, это может помочь.

Ответ 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);

Ответ 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);

Ответ 8

Хороший код для того, что я делаю в данный момент, но нашел ошибку. Я сохранял список целых чисел (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(','));
},

Ответ 9

Вот как вы храните и извлекаете массив в cookie с помощью json и jquery.

//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?

Ответ 13

Вот реализация JSON для работы с cookie, гораздо лучший способ хранения массивов. испытал с моего конца.

$.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: '/' });
          }
      };
  }

});