zoukankan      html  css  js  c++  java
  • js中cookie操作

    js中操作Cookie的几种常用方法

    * cookie中存在域的概念,使用path和domain区分;

    * 在同一域中的set和del可以操作同一名称的cookie,但不在同一域中的情况下,则set无法覆盖掉指定名称的cookie,del无法删除指定名称的cookie;

    获取cookie

    function getCookie(c_name){
        if (document.cookie.length>0){ 
            console.log(document.cookie);
            c_start=document.cookie.indexOf(c_name + "=");
            if (c_start!=-1){ 
                c_start=c_start + c_name.length+1; 
                c_end=document.cookie.indexOf(";",c_start);
                if (c_end==-1) c_end=document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            } 
        }
        return "";
    }

    设置cookie

    function setCookie(c_name,value,expiredays){
        var cookieStr = "";
        var exdate=new Date();
        exdate.setDate(exdate.getDate()+expiredays);
        document.cookie = c_name+ "=" +escape(value)+
        ((expiredays==null) ? "" : "; expires="+exdate.toGMTString())+";path=/";
    }//由于cookie存在域的概念,且在这里要不区分域,获取cookie的值,所以在这里使用的是统一的路径 path=/ ;

    删除cookie

    1.

    function delete_cookie( name, path, domain ) {
      if( get_cookie( name ) ) {
        document.cookie = name + "=" +
          ((path) ? ";path="+path:"")+
          ((domain)?";domain="+domain:"") +
          ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
      }
    }

    2.

    function delete_cookie( name ) {
      document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
    }

    3.

    function delCookie(c_name) 
    { 
        var exp = new Date(); 
        exp.setTime(exp.getTime() - 1); 
        var cval=getCookie(c_name);
        if(cval!=null) 
            document.cookie= c_name + "=;expires="+exp.toGMTString(); 
    } 

    参考资料:http://www.w3schools.com/js/js_cookies.asp

  • 相关阅读:
    黑苹果崩溃恢复
    黑苹果声音小解决方法
    idea plugin 进度条
    phpstorm 插件
    awesome mac
    webstorm vue eslint 自动修正配置
    Laravel/php 一些调试技巧
    php ZipArchive 压缩整个文件夹
    laravel 模型事件 updated 触发条件
    php 开启 opcache 之后 require、include 还会每次都重新加载文件吗?
  • 原文地址:https://www.cnblogs.com/springlight/p/5953153.html
Copyright © 2011-2022 走看看