zoukankan      html  css  js  c++  java
  • 前端对cookie的使用

    前端除了sessionStorage、localStorage之外,还有一种本地存储方式,即cookie。

    注意,要使用cookie,页面必须在服务器中运行,直接双击打开页面无法使用cookie。

    在进行微信公众号页面开发时,由于localStorage退出微信无法自动清除数据,而sessionStorage每次关闭页面就会清除数据。

    既想要退出微信可以清除数据,而关闭页面又仍有留有登录信息时,我们可以选择把token存储在cookie中。

    cookie相关代码如下所示:

    //设置自定义过期时间cookie
    function setCookie(name,value,time){
        var msec = getMsec(time); //获取毫秒
        var exp = new Date();
        exp.setTime(exp.getTime() + msec*1);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ";path=/";
    }
    //将字符串时间转换为毫秒,1秒=1000毫秒 function getMsec(str){ var timeNum=str.substring(0,str.length-1)*1; //时间数量 var timeStr=str.substring(str.length-1,str.length); //时间单位后缀,如h表示小时 if (timeStr=="s"){ //20s表示20秒 return timeNum*1000;} else if (timeStr=="h"){ //12h表示12小时 return timeNum*60*60*1000;} else if (timeStr=="d"){ return timeNum*24*60*60*1000;} //30d表示30天 }
    //读取cookies function getCookie(name){ var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); //正则匹配 if(arr=document.cookie.match(reg)){ return unescape(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() + ";path=/" } }

     其中的要点为:

    1.cookie存在document.cookie中。

    2.删除cookie则设置cookie的过期时间为当前时间-1。

    3.设置cookie时需要对value进行编码,即使用escape函数,取出时需要进行解码,即使用unescape函数。

    注:escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。

  • 相关阅读:
    MSSQL·阻止保存要求重新创建表的更改配置
    MSSQL·查询某数据库中所有表的记录数并排序
    异常处理·psftp·local unable to open
    MSSQL·Execution Timeout Expired. The timeout period elapsed prior to completion of the oper..
    MSSQL·ORDER BY 1 DESC是什么写法?
    MSSQL·大数据量历史数据清理的思路
    ubuntu清理wine卸载后的残余项目
    Learning the Vi Editor, 6th Edition O'Reilly Media
    做一粒不浮躁的好“种子”
    Qt Designer使用简易教程
  • 原文地址:https://www.cnblogs.com/luoyihao/p/12380677.html
Copyright © 2011-2022 走看看