Advertisement
vladislavkopilov

js cookie

Jul 5th, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //процедурное
  2. function writeCookie(name, value, days) {
  3.   var expires = "";
  4.   if (days) {
  5.     var date = new Date();
  6.     date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  7.     expires = "; expires=" + date.toGMTString();
  8.   }
  9.   document.cookie = name + "=" + value + expires + "; path=/";
  10. }
  11. function readCookie(name) {
  12.   var searchName = name + "=";
  13.   var cookies = document.cookie.split(';');
  14.   for(var i=0; i < cookies.length; i++) {
  15.     var c = cookies[i];
  16.     while (c.charAt(0) == ' ')
  17.       c = c.substring(1, c.length);
  18.     if (c.indexOf(searchName) == 0)
  19.       return c.substring(searchName.length, c.length);
  20.   }
  21.   return null;
  22. }
  23. function eraseCookie(name) {
  24.   writeCookie(name, "", -1);
  25. }
  26.  
  27. //ООП
  28. var jsCookie = {
  29.     writeCookie: function (name, value, days) {
  30.       var expires = "";
  31.  
  32.       if (days) {
  33.         var date = new Date();
  34.         date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
  35.         expires = "; expires=" + date.toGMTString();
  36.       }
  37.  
  38.       document.cookie = name + "=" + value + expires + "; path=/";
  39.     },
  40.  
  41.     readCookie: function (name) {
  42.       var searchName = name + "=";
  43.       var cookies = document.cookie.split(';');
  44.       for(var i=0; i < cookies.length; i++) {
  45.         var c = cookies[i];
  46.         while (c.charAt(0) == ' ')
  47.           c = c.substring(1, c.length);
  48.         if (c.indexOf(searchName) == 0)
  49.           return c.substring(searchName.length, c.length);
  50.       }
  51.       return null;
  52.     },
  53.  
  54.     eraseCookie: function (name){
  55.       writeCookie(name, "", -1);
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement