js Cookie

it2025-05-18  41

javascript操作Cookie

CreateTime--2017年6月2日17:15:36Author:Marydon

参考链接:http://www.jb51.net/article/64330.htm

(一)介绍  

  JavaScript是运行在客户端的脚本,因此一般是不能够设置Session的,因为Session是运行在服务器端的;

  而cookie是运行在客户端的,所以可以用JS来设置cookie。

(二)格式  

  cookie是以键值对的形式保存的,即key=value的格式。各个cookie之间一般是以“;”分隔。

/** * Cookie管理 */ function Cookie(){ var object = this; /** * 添加Cookie * @param sName * cookie名称 * @param sValue * cookie值 * @param expireTimes * cookie失效时间 */ this.SetCookie = function(sName, sValue, expireTimes) { var sCookie = sName + "=" + encodeURIComponent(sValue) + ";"; if (expireTimes) { expireTimes = object.getMilliseconds(expireTimes); if (null == expireTimes) return; var oDate = new Date(); oDate.setMilliseconds(oDate.getMilliseconds() + parseInt(expireTimes)); sCookie += "expires=" + oDate.toUTCString() + ";"; } // 添加Cookie document.cookie = sCookie; } /** * 获取Cookie * @param name * cookie名称 */ this.GetCookie = function(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) return decodeURIComponent(arr[2]); return null; } /** * 根据已知时间获取毫秒数 * @param time * cookie名称 * 参数格式:数字 + "s"/"m"/"h"/"d",如果没有加时间后缀,则按秒计算 */ this.getMilliseconds = function(time) { if (time) { // 转换成string time = time.toString(); // 截取除去最后一位的字符串 var str1 = time.slice(0, -1); // 截取最后一位 var str2 = time.slice(-1); if (str2 == "s")// return str1 * 1000; else if (str2 == "m")// return str1 * 60 * 1000; else if (str2 == "h")// return str1 * 60 * 60 * 1000; else if (str2 == "d")// return str1 * 24 * 60 * 60 * 1000; else return time * 1000; } return null; } }

  举例:

window.onload = function() { var cookie = new Cookie(); cookie.SetCookie("myName","zhangsan",60); alert(cookie.GetCookie('myName')) }

 

 相关推荐:

类似文章

 

 

转载于:https://www.cnblogs.com/Marydon20170307/p/6934356.html

相关资源:js 中存取 cookie 解决中文乱码
最新回复(0)