2

在我的 .aspx 页面中,当有人对投票进行投票时,我设置了一个 cookie,如下所示;

HttpContext.Current.Response.Cookies("poll")("poll_voted") = "yes"
HttpContext.Current.Response.Cookies("poll")("poll_id") = pID
HttpContext.Current.Response.Cookies("poll").Expires = Date.Now.AddDays(30)

现在,使用jquery cookie 插件,我需要检查 cookie 是否存在;

// this works quite well...
if ($.cookie('poll', { poll_voted: 'yes' })) {  
    // now here, I need to get the value of poll_id but how???
}

任何想法,将不胜感激。

4

2 回答 2

3

尝试添加这个插件 - 它要求 jquery.cookies.js 已经在页面上,我确信它可以使用一些调整,但对于我正在做的事情来说已经足够了。

(function ($, document) { 
    if($.cookie){
        $.cookieKey = function(CookieName, KeyName, Value, Options){
            var reg = new RegExp("(?:([^=]+)=([^&]*)&?)", "ig"),
            match = null,
            matches = [];
            var cookieVal = $.cookie(CookieName);
            while(match = reg.exec(cookieVal)){ 
                if(KeyName.toLowerCase() == match[1].toLowerCase()){
                    if(Value){ //we are updating, collect all values
                         matches.push([match[1], Value]);
                    }
                    else{
                        return match[2]; //we are getting, sub key found just return it
                    }
                }
                else if(Value){ //we are updating, collect all values
                    matches.push([match[1], match[2]]);
                }
            }                 

            if(Value){ //we are updating, update values
                updatedValue = "", 
                sep = "";
                for(i=0;i<matches;i++){
                    updatedValue += sep + matches[i][0] + "=" + matches[i][1];
                    sep = "&"
                }
                $.cookie(CookieName, updatedValue, Options);
            }           
            else return null;//we are getting, value not found
        }
    }
})(jQuery, document);

$.cookieKey("mycookiename", "keyname");//get sub key value
$.cookieKey("mycookiename", "keyname", "value");//set sub key value
$.cookieKey("mycookiename", "keyname", "value", {path: "/"});//set sub key value with cookie options
于 2013-07-11T14:51:36.110 回答
1

如果 $.cookie("poll") 是一个数组,这将起作用:

var mycookie = $.cookie("poll");
if(mycookie){
   var poll_id=mycookie["poll_id"];
}

您可以mycookie使用 firebug 或 chrome 开发人员工具检查变量的类型。

于 2012-06-30T21:23:11.640 回答