JavaScript操作cookie

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(); }

 

posted @ 2016-04-24 10:57  寂寞之砂  阅读(165)  评论(0编辑  收藏  举报