как сохранить массив в jquery cookie? - PullRequest
21 голосов
/ 24 декабря 2009

Мне нужно сохранить массив в файле cookie jQuery. Помогите, пожалуйста, мне?

Ответы [ 13 ]

57 голосов
/ 25 декабря 2009

Все еще не совсем уверен, что вам нужно, но я надеюсь, что это поможет. Это образец, который позволит вам получить доступ к элементам на любой странице, это просто образец! Он использует 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.

Добавление элементов в список 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. Снова надеюсь, что это поможет.

EDIT См. Браво ответ, если у вас есть проблемы с IE

11 голосов
/ 24 декабря 2009

Загрузите плагин 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 голосов
/ 13 декабря 2013

Я не знаю, поможет ли это кому-нибудь, но мне также нужна была функция, которая проверяет, есть ли уже элемент, поэтому я не добавляю его снова.

Я использовал ту же функцию удаления и изменил ее, чтобы она содержала функцию:

"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;
}
},
3 голосов
/ 02 июня 2012

Я получаю сообщение об ошибке при попытке использовать сценарий 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.

и поэтому я добавляю сюда другую базу кода Как исправить 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(','));
},

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

3 голосов
/ 08 апреля 2012

Проверьте мою реализацию (как плагин 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();
2 голосов
/ 01 августа 2014

Так вы сохраняете и извлекаете массив в 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. 
2 голосов
/ 02 марта 2014

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

Я немного скорректировал пример для использования кодировки 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);
2 голосов
/ 14 апреля 2012

Эта реализация обеспечивает независимый доступ для нескольких элементов управления на странице:

(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 голос
/ 24 января 2012

просто небольшая альтернатива функции "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"];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...