function Cookies(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
var path = options.path ? '; path=' + (options.path) : '/';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].replace(/^\s+|\s+$/g, "");
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
}
这是一个存入Cookie和获取的函数
调用:第一个参数键名,第二个参数值,第三个参数 路径和过期时间
Cookies("val", str, { path: '/', expires: 10 });
到了.Net里,因为我在后台写Cookie都是指定某个域下的,如果是要获取前台的path '/' 就不指定
获取域中的Cookie
/// <summary>
/// 获得cookie值
/// </summary>
/// <param name="strName">项</param>
/// <returns>值</returns>
public static string GetCookie(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies["shikee.com"] != null &&
HttpContext.Current.Request.Cookies["shikee.com"][strName] != null)
{
return Utils.UrlDecode(HttpContext.Current.Request.Cookies["shikee.com"][strName].ToString());
}
return null;
}
不指定shikee.com域
传入的strName就是JS传入的键名,这样就找到path为"/"下的Cookie
public static string GetCookie_path(string strName)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
{
Encoding encoding = Encoding.GetEncoding("UTF-8");
return HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[strName].Value, encoding);
}
return null ;
}