jak przechowywać tablicę w pliku cookie jquery?

Muszę zapisać tablicę w ciastku jQuery, ktoś mi pomoże?

Author: Gumbo, 2009-12-24

13 answers

Nadal Nie wiem, czego potrzebujesz, ale mam nadzieję, że to pomoże. Jest to próbka, która pozwoli ci uzyskać dostęp do elementów na dowolnej stronie, to tylko próbka! Używa nazwy cookieName, aby zidentyfikować ją na stronach.

//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;
    }
  }
}  

Więc na każdej stronie można uzyskać takie przedmioty.

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

Dodawanie pozycji do cookieList

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

Uzyskanie wszystkich elementów jako tablicy

alert(list.items());

Czyszczenie elementów

list.clear();

Możesz dodać dodatkowe rzeczy, takie jak push i pop całkiem łatwo. Mam nadzieję, że to pomoże.

EDIT Zobacz odpowiedź bravos, jeśli masz problemy z IE

 57
Author: almog.ori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-05 11:05:41

Pobierz wtyczkę jQuery cookie tutaj: http://plugins.jquery.com/project/Cookie

Ustawienie pliku cookie za pomocą jQuery jest tak proste, jak to, gdzie tworzymy plik cookie o nazwie "example" o wartości ["foo1","foo2"]

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

Uzyskanie wartości pliku cookie jest również bardzo łatwe dzięki jQuery. Poniżej przedstawiono wartość "przykładowego" pliku cookie w oknie dialogowym

alert( $.cookie("example") );
 10
Author: almog.ori,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-12-24 19:49:57

Sprawdź moją implementację (jako wtyczkę 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);

Użycie:

  var cookieList = $.fn.cookieList("cookieName");
  cookieList.add(1);
  cookieList.add(2);
  cookieList.remove(1);
  var index = cookieList.indexOf(2);
  var length = cookieList.length();
 3
Author: Pavel Shkleinik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-08 09:29:02

Dostałem błąd, gdy próbuję użyć almog.skrypt ori w 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;
        }
      }

}  

Po kilku godzinach kopania błędu, zdałem sobie sprawę, że indexOf w

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

Nie obsługuje IE 8.

I tak dodaję kolejną bazę kodu stąd Jak naprawić Array indexOf () w JavaScript dla przeglądarek Internet Explorer

To działa,

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

Na wypadek, gdyby ktoś odkrył, że skrypt nie działa w IE 8, może to pomóc.

 3
Author: bravo net,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:24:37

Nie wiem, czy to komuś pomoże, ale potrzebowałem również funkcji, która sprawdza, czy Element już tam jest, więc nie dodaję go ponownie.

Użyłem tej samej funkcji remove i zmieniłem ją na funkcję contain:

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

Z jakiegoś powodu powyższy kod nie zawsze działa. oto nowy, który działa:

"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
Author: alhoseany,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-13 23:06:50

Ta implementacja zapewnia niezależny dostęp dla wielu kontrolek na stronie:

(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
Author: Pavel Shkleinik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-14 11:05:33

Lekko dostosowałem przykład, aby używać kodowania JSON i dekodowania secureJSON, co czyni go bardziej wytrzymałym i oszczędzającym.

Zależy od 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
Author: Wessel dR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-20 13:58:43

Ładny kawałek kodu do tego, co robię w tej chwili, ale znalazłem błąd. Zapisywałem listę liczb całkowitych (ID) do pliku cookie. Jednak gdy plik cookie jest po raz pierwszy odczytany, wpisuje się do ciągów. Wcześniej zapisałem (int) 1, a później, gdy plik cookie zostanie pobrany na stronie przeładowanie oznacza go jako "1". Tak więc, kiedy próbuję usunąć (int) 1 z listy, nie będzie indeksować dopasowania.

Poprawka, którą zastosowałem polega na zmianie wyrażenia " val " NA val.toString () przed dodaniem lub indeksowaniem elementów. Tak więc items jest tablicą łańcuchów.

"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
Author: user3369864,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-02 03:57:13

W ten sposób przechowujesz i pobierasz tablicę w pliku cookie za pomocą json i 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
Author: Susie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-31 22:28:58

Dodałem akcję "remove" do tego kto chce z niej korzystać - val jest indeksem, od którego należy zacząć zmieniać tablicę:

    "remove": function (val) {
        items.splice(val, 1);
        $.cookie(cookieName, items.join(','));
    }
 1
Author: Assaf Vilmovski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-18 20:09:35

Mała alternatywa dla funkcji "remove":

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

Gdzie val jest wartością elementu w tablicy np.:

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

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

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

   ["foo1", "foo3"];
 1
Author: Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-24 01:52:17

Można serializować tablice przed zapisaniem jako cookie, a następnie deserializować podczas czytania. ie z jsonem?

 0
Author: Flobo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-05-24 22:37:57

Oto JSON implementacja do pracy z plikami cookie, znacznie lepszy sposób na przechowywanie tablic . sprawdzone od mojej strony.

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

});

 0
Author: Mohan Dere,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-17 04:02:44