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");取值。