cookie的简单操作

作者:互联网   出处:控件中国网   2014-11-05 19:05:23   阅读:1

cookie的简单操作

在网站应用程序中经常会用到cookie,那么写入cookie和读取cookie就成了常见操作了

HttpCookie newcook = new HttpCookie("logis");
newcook.Expires.AddMinutes(30);
newcook.Values.Add("user_name", HttpUtility.UrlEncode(offerName, Encoding.UTF8));
HttpContext.Current.Response.AppendCookie(newcook);
 

javascript读取写入的cookie:

function GetCookie(sMainName, sSubName) {  
        var sCookieName = sMainName + "=";  
        var sSubCookieName = (sSubName) ? sSubName + "=" : null;  
        var sCookie;  
        var sWholeCookie = document.cookie;  
 
        var nValueBegin = sWholeCookie.indexOf(sCookieName);  
        if (nValueBegin != -1) {  
            var nValueEnd = sWholeCookie.indexOf(";", nValueBegin);  
            if (nValueEnd == -1)
   {
                nValueEnd = sWholeCookie.length;
   } 
            var sValue = sWholeCookie.substring(nValueBegin + sCookieName.length, nValueEnd); //获得Cookie值
            if (sSubCookieName)
            {  
                var nSubValueBegin = sValue.indexOf(sSubCookieName);  
                if (nSubValueBegin != -1)
    {  
                    var nSubValueEnd = sValue.indexOf("&", nSubValueBegin);  
                    if (nSubValueEnd == -1)
     {
                        nSubValueEnd = sValue.length; 
     }
                    var sSubValue = sValue.substring(nSubValueBegin + sSubCookieName.length, nSubValueEnd); //获得指定的子键值  
                    //return unescape(sSubValue); 
     return decodeURIComponent(sSubValue); 
                }  
            }  
            if (!sSubCookieName)
   {
                //return unescape(sValue);
    return decodeURIComponent(sValue);
   }
        }  
        return null;  
    }  

直接通过GetCookie("logis","user_name");取值。

 

Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat