参考链接: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'))
}

  说明:

  同名的cookie只能存在一个,如果重名,后面的覆盖前面的,大小写敏感!

 相关推荐:

 

 

相关文章:

  • 2021-08-06
  • 2022-12-23
  • 2021-12-04
猜你喜欢
  • 2022-12-23
  • 2021-09-30
  • 2021-04-03
相关资源
相似解决方案