js操作cookie的方法

版权声明:本文为博主原创文章,转载时请标注原创地址。 https://blog.csdn.net/u014346301/article/details/52575395

cookie

cookie,有时候也用其复数形式Cookies,指某些网站为了辨别用户身份,进行session跟踪而储存在用户本地终端上的数据(经常通过加密)。定义于RFC2109和2965都已废弃,最新取代的规范是RFC6265。

cookie的作用

服务器可以利用Cookie包含信息的任意性来筛选经常性维护这些信息,以判断在HTTP传输中的状态。Cookie最典型的英语是判断注册用户是否已经登录网站,用户可能会得到提示,是否在下一次进入此网站时保留用户信息以便简化登录步骤,浙西都是Cookie的功能。另一个重要张合是“购物车”之类处理。用户可能会在一段时间内在同一家网站的不同页面中选择不同的商品,这些信息都会写入Cookie,以便在最后付款时提取信息。

js设置cookie

document.cookie="key=value";
//例
document.cookie="name=weiqi";

//可以在控制台中打印出cookie
console.log(document.cookie);

如何修改和获取cookie

js中并没有提供获取cookie的方法,所以只能自己封装方法,相同的key的cookie只能存在一个,如果定义了一个document.cookie="age=21",后面又定义了document.cookie="age=30",那么后面定义的cookie会覆盖前面定义的cookie,所以修改cookie值的时候只用重新定义个key相同的cookie就可以了。那么获取cookie的时候也只用在cookie中获取到这个key后面的“=”和“;”直接的字符串,那就是这个cookie的值了,获取的方法又很多种,这里我写一种比较简单的:

function getCookie(key){
    var index = document.cookie.indexOf(key);
    var returnValue;
    if(index!==-1){
        var tIndex = document.cookie.indexOf(";",index);
        var target = document.cookie.substring(index,tIndex);
        var returnValue = decodeURIComponent(target.replace(key+"=",""))
    }
    return returnValue;
}

document.cookie="name=weiqi";
getCookie("name");  //weiqi

删除cookie

cookie是有有效期的,前面我们设置cookie的时候都没有设置有效期,如果我们将cookie的有效期设置成一个已经过去的时间,那么它就无效了,下面来实现一下:

function delCookie(key){
    var d = new Date();
    document.cookie=key+"=;expires="+ d.toGMTString();
}

document.cookie="name=weiqi";
delCookie("name");  //undefined

给cookie设置一个有效期

通过expires给cookie设置一个有效期,现在我们设置一个cookie的有效期是10天,如下:

var d = new Date();
var time = 10;
d.setTime(d.getTime()+time*1000*60*60*24);
document.cookie="name=weiqi;expires="+ d.toGMTString();

封装cookie

将自定义的一些方法完善一下封装成一个对象,这样在使用的时候就可以直接拿来用了:

//封装cookie方法的对象
var cookie = {
    setCookie:function(key,value,time){
        if(key == undefined){
            return;
        }
        if(time!== undefined){
            var d = new Date();
            d.setTime(d.getTime()+time*1000*60*60*24);
            document.cookie=key+"="+value+";expires="+ d.toGMTString();
        }else{
            document.cookie=key+"="+value;
        }
    },
    getCookie:function(key){
        var index = document.cookie.indexOf(key);
        var returnValue;
        if(index!==-1){
            var tIndex = document.cookie.indexOf(";",index);
            var target = document.cookie.substring(index,tIndex);
            var returnValue = decodeURIComponent(target.replace(key+"=",""))
         }
        return returnValue;
    },
    delCookie:function(key){
        var d = new Date();
        document.cookie=key+"=;expires="+ d.toGMTString();
    }
}


//测试
cookie.setCookie("home")
cookie.setCookie("name","卫旗");
cookie.setCookie("age",22);
cookie.setCookie("sex","男")
cookie.getCookie("sex")
cookie.delCookie("age")
展开阅读全文

js操作cookie的疑惑

01-06

[code=JScript]function Cookie(name)rn this.$name = name; rn var allcookies = document.cookie;rn if(allcookies == "")return;rn var cookies = allcookies.split(";");rn var cookie = null;rn for(var i = 0; i < cookies.length; i++)rn // Does this cookie string begin with the name we want?rn if (cookies[i].substring(0, name.length+1) == (name + "="))rn cookie = cookies[i];rn break;rn rn rn if (cookie == null) return;rn var cookieval = cookie.substring(name.length+1);rn var a = cookieval.split("&");rn for(var i=0; i < a.length; i++)rn a[i] = a[i].split(":");rn rn for(var i=0; i < a.length; i++)rn this[a[i][0]] = decodeURIComponent(a[i][1]);rn rn rn/**rn* This function is the store() method of the Cookie object.rn*rn* Arguments:rn*rn* daysToLive: the lifetime of the cookie, in days. If you set thisrn* to zero, the cookie will be deleted. If you set it to null, orrn* omit this argument, the cookie will be a session cookie and willrn* not be retained when the browser exits. This argument is used torn* set the max-age attribute of the cookie.rn* path: the value of the path attribute of the cookiern* domain: the value of the domain attribute of the cookiern* secure: if true, the secure attribute of the cookie will be setrn*/ rn Cookie.prototype.store = function(daysToLive, path, domain, secure)rn var cookieval = "";rn for(var prop in this)rn if ((prop.charAt(0) == "$") || ((typeof this[prop]) == "function"))rn continue;rn if (cookieval != "") cookieval += "&";rn cookieval += prop + ":" + encodeURIComponent(this[prop]);rn rn var cookie = this.$name + "=" + cookieval;rn if (daysToLive || daysToLive == 0)rn cookie += "; max-age=" + (daysToLive*24*60*60);rn rn if (path) cookie += "; path=" + path;rn if (domain) cookie += "; domain=" + domain;rn if (secure) cookie += "; secure";rn rn document.cookie = cookie;rn ;rn rn/**rn* This function is the remove() method of the Cookie object; it deletes thern* properties of the object and removes the cookie from the browser'srn* local store.rn*rn* The arguments to this function are all optional, but to remove a cookiern* you must pass the same value you passed to store().rn*/rn Cookie.prototype.remove = function(path,domain, secure)rn for(var prop in this)rn if (prop.charAt(0) != "$" && typeof this[prop] != "function")rn delete this[prop];rn rn this.store(0,path,domain,secure);rn ;rn rn/**rn* This static method attempts to determine whether cookies are enabled.rn* It returns true if they appear to be enabled and false otherwise.rn* A return value of true does not guarantee that cookies actually persist .rn* Nonpersistent session cookies may still work even if this methodrn* return false.rn*/rn Cookie.enabled = function()rn if (navigator.cookieEnabled != undefined) return navigator.cookieEnabled;rn if (Cookie.enabled.cache != undefined) return Cookie.enabled.cache;rn document.cookie = "testcookie=test; max-age=10000";rn var cookies = document.cookie;rn if (cookies.indexOf("testcookie=test") == -1)rn return Cookie.enable.cache = false;rn rn elsern document.cookie = "testcookie=test; max-age=0";rn return Cookie.enable.cache = true;rn rn ;[/code]rnrn上面是从js权威指南上摘抄下来的代码rnrn按照代码 , 我是这样操作的cookie rn[code=JScript]rn var cookie=new Cookie('docman'); rn cookie.close=1;rn cookie.store(1,"/");rn[/code]rn这样的话 我只要在同意域名下,就能读取到这个cookie,但是 我只要离开设置cookie的页面就读取不到了 rnrn求解 , 我用的是火狐和google的浏览器 。。。。。rn可能是我水平实在有限rn望高人指教 论坛

没有更多推荐了,返回首页