Help us understand the problem. What is going on with this article?

JavaScriptでCookieを扱う

More than 5 years have passed since last update.

連想配列をCookieに保存したり、Cookieを連想配列で取り出したり出来る関数

Cookieに値と有効期間を保存

JavaScript
// data・・・cookieに格納する連想配列
// period・・・cookieの有効期間(日)
var setCookie = (function(){
 return function(data, period) {
  var cookies = '';
  for (var key in data) {
   cookies += key + '=' + encodeURIComponent(data[key]) + '; ';
  }

  var expire = new Date();
  expire.setTime( expire.getTime() + 1000 * 3600 * 24 * period);
  expire.toUTCString();

  cookies += 'expires=' + expire+';';

  document.cookie = cookies;
 };
})();

Cookieから値を連想配列に変換して取得

JavaScript
var getCookie = (function(){
 return function() {
  var result = [];
  var cookies = document.cookie;

  if(cookies != ''){
   var cookieArray = cookies.split(';');
   for(var i = 0; i < cookieArray.length; i++){
    var cookie = cookieArray[i].split('=');
    result[cookie[0]] = decodeURIComponent(cookie[1]);
   }
  }
  return result;
 };
})();
Evolutor_web
Webサイトを中心にいろいろとやってる人。FlashやらHTMLやらPHPやらJavaScriptやらもろもろ。 趣味はPC/Mac、スマホ、音楽、サバゲ、東方。 つまり、金のかかるただのオタク。
http://www.evolutor.net/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away