js中cookie的用法

来源:互联网 发布:人工智能就业 知乎 编辑:程序博客网 时间:2024/06/05 07:49

在实际开发项目中,经常会用到cookie,下面是我在实际项目中所用到的,与大家分享下,欢迎留言。

一 js给cookie 设值

      function setCookie(){
        
       //(1)cookie有效期1天,可自行设置
        var days = 1;//设置cookie保存一天
        var exp = new Date();//获取当前时间
        exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);//换成毫秒
        document.cookie =  "name=list;expires=" + exp.toGMTString();

       //(2)cookie有效期随着会话结束而消失
        document.cookie =  "name=list" ;
    }

二 js获取cookie值

     function getCookie(){

       var search =  "name="//查询检索的值
       var returnvalue = "";//获取的cookie值
       if (document.cookie.length > 0) {
          sd = document.cookie.indexOf(search);
         if (sd!= -1) {
            sd += search.length;
            end = document.cookie.indexOf(";", sd);
    if (end == -1)
    end = document.cookie.length;
    //unescape() 函数可对通过 escape() 编码的字符串进行解码。
     returnvalue=unescape(document.cookie.substring(sd, end))
    }

alert( returnvalue);
    }
原创粉丝点击