0

我想知道 jquery 是否可以检查 cookie 数组是否存在。

我的 cookie 名称是 'report' 并且使用 php 我像这样回显它:

echo '<pre>'; print_r($_COOKIE['report'][146]); echo '</pre>';

吐出这样的东西:

Array
(
    [15128] => 15128
    [13670] => 13670
)

这是我希望让 jquery 检查上面的 cookie 数组是否存在(或不存在)的地方,这是我到目前为止所得到的,但它没有拾取 cookie 数组。

if ( $.cookie('report[146]') ) {
  window.location = 'http://www.myurl.com/';
} else {
  alert('Please make a selection.');
}

当有人勾选复选框时,我的表单不会刷新,但它使用 jquery 添加 cookie(工作正常),但我似乎无法让 jquery 检查是否有任何 cookie。

这是将单个 cookie 添加到数组的代码:

if ($(this).attr('checked')) { 
  $.cookie('report[146]['+thisID+']', thisID, { expires: 7, path: '/' });
} else {
  $.cookie('report[146]['+thisID+']', thisID, { expires: -1, path: '/' });
};

任何帮助,将不胜感激!

4

2 回答 2

2
if($.cookie('report') == null) { 
    alert('no cookie!');
}
于 2012-09-10T06:06:22.243 回答
2

您现在正在做的是设置名为的 cookie report[146]['+thisID+'](例如,如果 thisID = 135,则 cookie 名称为report[146][135])。cookie 的值不是数组,该 cookie 的值是thisID.

如果您希望 cookie 具有 namereport并且它的 value 应该是索引 146 具有 value 的数组thisID,请执行以下操作:

var cookieValue = [];
cookieValue[146] = thisID;

设置它:

$.cookie('report', cookieValue);

Cookie 值现在将设置为(这就是数组序列化的方式):

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,135

要阅读它:

var cookie = $.cookie('report');
if(cookie){
  var cookieValue = cookie.split(','); //you need to do this since array is serialized as comma separated values.
  var valueAtIndex146 = cookieValue[146];
}
于 2012-09-10T06:41:17.780 回答