zoukankan      html  css  js  c++  java
  • js设置cookie(原生js)

    cookie 与 session 是网页开发中常用的信息存储方式。Cookie是在客户端开辟的一块可存储用户信息的地方;Session是在服务器内存中开辟的一块存储用户信息的地方.

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

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

    假设有这样一种情况,在某个用例流程中,由A页面跳至B页面,若在A页面中采用JS用变量temp保存了某一变量的值,在B页面的时候,同样需要使用JS 来引用temp的变量值,对于JS中的全局变量或者静态变量的生命周期是有限的,当发生页面跳转或者页面关闭的时候,这些变量的值会重新载入,即没有达到 保存的效果。解决这个问题的最好的方案是采用cookie来保存该变量的值,那么如何来设置和读取cookie呢?

    首先需要稍微了解一下cookie的结构,简单地说:cookie是以键值对的形式保存的,即key=value的格式。各个cookie之间一般是以“;”分隔。

    JS设置cookie:
     


    假设在A页面中要保存变量username的值("jack")到cookie中,key值为name,则相应的JS代码为:

    document.cookie="name="+username;  

    JS读取cookie:
     
    假设cookie中存储的内容为:name=jack;password=123
     
    则在B页面中获取变量username的值的JS代码如下:

    var username=document.cookie.split(";")[0].split("=")[1];  

    //JS操作cookies方法!

    //写cookies

    function setCookie(name,value)
    {
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days*24*60*60*1000);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();

        
        var strsec = getsec(time);
        var exp = new Date();
        exp.setTime(exp.getTime() + strsec*1);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    }

    //读取cookies
    function getCookie(name)
    {
        var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
     
        if(arr=document.cookie.match(reg))
     
            return (arr[2]);
        else
            return null;
    }

    //删除cookies
    function delCookie(name)
    {
        var exp = new Date();
        exp.setTime(exp.getTime() - 1);
        var cval=getCookie(name);
        if(cval!=null)
            document.cookie= name + "="+cval+";expires="+exp.toGMTString();
    }
    //使用示例
    setCookie("name","hayden");
    alert(getCookie("name"));

    //如果需要设定自定义过期时间
    //那么把上面的setCookie 函数换成下面两个函数就ok;


    //程序代码
    function setCookie(name,value,time)
    {
        var strsec = getsec(time);
        var exp = new Date();
        exp.setTime(exp.getTime() + strsec*1);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    }

    function getsec(str)
    {
       alert(str);
       var str1=str.substring(1,str.length)*1;
       var str2=str.substring(0,1);
       if (str2=="s")
       {
            return str1*1000;
       }
       else if (str2=="h")
       {
           return str1*60*60*1000;
       }
       else if (str2=="d")
       {
           return str1*24*60*60*1000;
       }
    }
    //这是有设定过期时间的使用示例:
    //s20是代表20秒
    //h是指小时,如12小时则是:h12
    //d是天数,30天则:d30

    setCookie("name","hayden","s20");//在谷歌浏览器中需要在服务器中才能响应
    将cookie值存到响应域名中的方法如下:
    <script>
    String.prototype.trim = function(){ return Trim(this);};
    function LTrim(str)
    {
     
       var i;
        for(i=0;i<str.length;i++)
        {
            if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
        }
        str=str.substring(i,str.length);
        return str;
    }
    function RTrim(str)
    {
        var i;
        for(i=str.length-1;i>=0;i--)
        {
            if(str.charAt(i)!=" "&&str.charAt(i)!=" ")break;
        }
        str=str.substring(0,i+1);
        return str;
    }
    function Trim(str)
    {
        return LTrim(RTrim(str));
    }
    function cookie(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString();
            }
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = (cookies[i]).trim();
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    window.onload = function(){
         cookie('ddd','12345666666',{expires: 7, path: '/', domain: 'jquery.com', secure: true});
         alert(cookie('ddd'));
    }
    </script>
    第三种包括删除cookie:
    var config = $.cookie = function(key, value, options) {

            // Write
            if (value !== undefined && !$.isFunction(value)) {
                options = $.extend({}, config.defaults, options);

                if (typeof options.expires === 'number') {
                    var days = options.expires,
                        t = options.expires = new Date();
                    t.setDate(t.getDate() + days);
                }

                return (document.cookie = [
                    encode(key), '=', stringifyCookieValue(value),
                    options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
                    options.path ? '; path=' + options.path : '',
                    options.domain ? '; domain=' + options.domain : '',
                    options.secure ? '; secure' : ''
                ].join(''));
            }

            // Read

            var result = key ? undefined : {};

            // To prevent the for loop in the first place assign an empty array
            // in case there are no cookies at all. Also prevents odd result when
            // calling $.cookie().
            var cookies = document.cookie ? document.cookie.split('; ') : [];

            for (var i = 0, l = cookies.length; i < l; i++) {
                var parts = cookies[i].split('=');
                var name = decode(parts.shift());
                var cookie = parts.join('=');

                if (key && key === name) {
                    // If second argument (value) is a function it's a converter...
                    result = read(cookie, value);
                    break;
                }

                // Prevent storing a cookie that we couldn't decode.
                if (!key && (cookie = read(cookie)) !== undefined) {
                    result[name] = cookie;
                }
            }

            return result;
        };

        config.defaults = {};

        $.removeCookie = function(key, options) {
            if ($.cookie(key) !== undefined) {
                // Must not alter options, thus extending a fresh object...
                $.cookie(key, '', $.extend({}, options, {
                    expires: -1
                }));
                return true;
            }
            return false;
        };
     
    使用方法:
    $.cookie('app_usertype', d.data.type);
    $.removeCookie('app_usertype');
    $.removeCookie('app_usertype', {
                    path: '/'
     });
  • 相关阅读:
    分治6--循环比赛日程表
    分治5--一元三次方程求解
    分治4--快速排序
    分治3--黑白棋子的移动
    分治2--取余运算
    分治1--二分查找
    贪心6--整数区间
    贪心5--活动选择
    贪心4--拦截导弹
    贪心3--删数问题
  • 原文地址:https://www.cnblogs.com/dearxinli/p/4205479.html
Copyright © 2011-2022 走看看