2012-06-30 63 views
2

在我的.aspx頁面中,我設置了一個cookie,當有人投票時如下投票:如何使用jquery cookie插件獲取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 plugin我需要檢查cookie是否存在;

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

任何想法,將不勝感激。

回答

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 
1

如果$ .cookie( 「調查」)是一個數組,這會工作:

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

你可以使用Firebug或Chrome開發者工具檢查mycookie變量的類型。