js cookie

(二少)在南極發表於2013-11-20

   SetCookie: function (name, value)//設定Cookie值 
    {
        var expdate = new Date();
        var argv = arguments;
        var argc = arguments.length;
        var expires = (argc > 2) ? argv[2] : null;
        var path = (argc > 3) ? argv[3] : null;
        var domain = (argc > 4) ? argv[4] : null;
        var secure = (argc > 5) ? argv[5] : false;
        if (expires != null) expdate.setTime(expdate.getTime() + (expires * 1000));
        document.cookie = name + "=" + escape(value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString()))
   + ((path == null) ? "" : ("; path=" + path)) + ((domain == null) ? "" : ("; domain=" + domain))
   + ((secure == true) ? "; secure" : "");
    },
    DelCookie: function (name)//刪除Cookie 
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval = GetCookie(name);
        document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
    },
    GetCookie: function (cookieName) {
        var cookieString = document.cookie;
        var start = cookieString.indexOf(cookieName + '=');
        if (start == -1) return null; // 加上等號的原因是避免在某些 Cookie 的值裡有與cookieName一樣的字串 
        start += cookieName.length + 1;
        var end = cookieString.indexOf(';', start);
        if (end == -1) return unescape(cookieString.substring(start));
        return unescape(cookieString.substring(start, end));
    }

相關文章