如何使用jquery(或只是javascript)迭代cookie?

时间:2022-03-23 14:31:10

I am using the "Cookie Plugin" by Klaus Hartl to add or update cookies at $(document).ready. I have another event that is supposed to iterate all the cookies and do something with the value of each cookie. How can I iterate over the collection of cookies and get the id and value of each?

我使用Klaus Hartl的“Cookie插件”在$(document).ready上添加或更新cookie。我有另一个事件,应该迭代所有的cookie,并使用每个cookie的值做一些事情。如何迭代cookie集合并获取每个cookie的ID和值?

I'm thinking something like this:

我在想这样的事情:

$.cookie.each(function(id, value) { 
            alert('ID='+id+' VAL='+value); 
        });

3 个解决方案

#1


19  

If you just want to look at the cookies it's not that hard without an extra plugin:

如果您只想查看cookie,没有额外的插件就不那么难了:

$.each(document.cookie.split(/; */), function()  {
  var splitCookie = this.split('=');
  // name is splitCookie[0], value is splitCookie[1]
});

#2


4  

well it's rather easy in plain javascript:

在简单的javascript中它很容易:

var keyValuePairs = document.cookie.split(';');
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
}

#3


0  

The other solution does create white spaces before the name, which gives hard to debug errors.

另一个解决方案确实在名称之前创建了空格,这使得难以调试错误。

var keyValuePairs = document.cookie.split(/; */);
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
    ...

#1


19  

If you just want to look at the cookies it's not that hard without an extra plugin:

如果您只想查看cookie,没有额外的插件就不那么难了:

$.each(document.cookie.split(/; */), function()  {
  var splitCookie = this.split('=');
  // name is splitCookie[0], value is splitCookie[1]
});

#2


4  

well it's rather easy in plain javascript:

在简单的javascript中它很容易:

var keyValuePairs = document.cookie.split(';');
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
}

#3


0  

The other solution does create white spaces before the name, which gives hard to debug errors.

另一个解决方案确实在名称之前创建了空格,这使得难以调试错误。

var keyValuePairs = document.cookie.split(/; */);
for(var i = 0; i < keyValuePairs.length; i++) {
    var name = keyValuePairs[i].substring(0, keyValuePairs[i].indexOf('='));
    var value = keyValuePairs[i].substring(keyValuePairs[i].indexOf('=')+1);
    ...