How to get cookie subkeys with jquery cookie plugin?
-
18-06-2021 - |
题
In my .aspx page, I set a cookie when someone votes on a poll as follows;
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)
now, with jquery cookie plugin I need to check if a cookie exists;
// this works quite well...
if ($.cookie('poll', { poll_voted: 'yes' })) {
// now here, I need to get the value of poll_id but how???
}
Any ideas would be appreciated.
解决方案
Try adding this plugin - it requires that jquery.cookies.js is already on the page, and I'm sure it could use some tweaking but it was good enough for what I was doing.
(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
其他提示
if $.cookie("poll") is an array, this would work:
var mycookie = $.cookie("poll");
if(mycookie){
var poll_id=mycookie["poll_id"];
}
you can check the type of mycookie
variable with firebug or chrome developer tools.
不隶属于 StackOverflow