zoukankan      html  css  js  c++  java
  • Javascript(JS)对Cookie的读取、删除、写入操作帮助方法

     1 var CookieUtils = {
     2     get: function (name) {
     3         var cookieName = encodeURIComponent(name) + '=',
     4             cookieStart = document.cookie.indexOf(cookieName),
     5             cookieValue = null;
     6         if (cookieStart > -1) {
     7             var cookieEnd = document.cookie.indexOf(';', cookieStart);
     8             if (cookieEnd == -1) {
     9                 cookieEnd = document.cookie.length;
    10             }
    11             cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    12         }
    13         return cookieValue;
    14     },
    15     set: function (name, value, expires, path, domain, secure) {
    16         var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
    17         if (expires instanceof Date) {
    18             cookieText += "; expried=" + expires.toGMTString();
    19         }
    20         if (path) {
    21             cookieText += "; path=" + path;
    22         }
    23         if (domain) {
    24             cookieText += "; domain=" + domain;
    25         }
    26         if (secure) {
    27             cookieText += "; secure";
    28         }
    29         document.cookie = cookieText;
    30     },
    31     unset: function (name, path, domain, secure) {
    32         this.set(name, "", new Date(0), path, domain, secure);
    33     }
    34 }

    这样即可以调用CookieUtils.get/set/unset方法进行Cookie操作。

    项目完成后会对本方法进行进一步完善。

    参考自《Javascript高级程序设计》

  • 相关阅读:
    python基础#1
    shell脚本基础练习题
    shell计算100以内加法
    shell脚本添加用户
    python学习ing
    框架
    前端
    python基础之数据类型-面向对象
    python四种列表的插入方法及其效率
    Charles高阶操作
  • 原文地址:https://www.cnblogs.com/xidu/p/js_cookie.html
Copyright © 2011-2022 走看看