码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript操作cookie

时间:2016-04-24 12:37:09      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

1、设置cookie

    /**
     * 设置cookie
     */
    function setCookie(name, value) {
        //获取当前时间
        var date = new Date();
        var expireDays = 10;
        date.setTime(date.getTime() + expireDays * 24 * 3600 * 1000);
        //将userId和userName两个cookie设置为10天后过期
        document.cookie = name + "=" + value + ";path=/;expire=" + date.toGMTString();
    }

2、获取cookie

function getToken(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

    if (arr = document.cookie.match(reg))

        return unescape(arr[2]);
    else
        return null;
};

3、删除cookie

    /**
     * 删除cookie
     * @param name
     */
    function deleteCookie(name) {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = getCookie(name);
        if (cval != null)
            document.cookie = name + "=" + cval + ";path=/;expires=" + exp.toGMTString();
    //在从cookie删除   
var domainInfoArray = document.domain.split(".");    document.cookie = name + "=" + cval + ";domain=." + domainInfoArray[domainInfoArray.length - 2] + "." + domainInfoArray[domainInfoArray.length - 1] + ";path=/;expires=" + exp.toGMTString(); }

 

JavaScript操作cookie

标签:

原文地址:http://www.cnblogs.com/sanqianjin/p/5426526.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!