JavaScriptでCookieを
JavaScriptでCookieを使ってみる。
参考:
[JavaScript + Cookie]実は有効期限指定がすごく簡単だった件について
<!DOCTYPE HTML> <html lang="ja"> <head><meta charset="UTF-8"> <script type="text/javascript"> <!-- function printf( value ) { var out = document.getElementById("out"); var str = out.innerHTML; out.innerHTML = str +"\n"+ value +"<br>\n"; } var Cookie = { get: function(name) { printf("Loading..."); var match = ('; ' + document.cookie + ';').match('; ' + name + '=(.*?);'); printf( "<b>Load Cookie</b>:" + match ? decodeURIComponent(match[1]) : '' ); return match ? decodeURIComponent(match[1]) : ''; }, set: function(name, value, option ) { // option : { expires, domain, path, secure } printf("Writing..."); console.log( arguments ); if( typeof name != 'undefined' && name != '' && typeof value != 'undefined' && value != '' ) { var buffer = name + '=' + encodeURIComponent(value); if (typeof option.expires != 'undefined' && option.expires != '' ) buffer += '; expires=' + new Date(option.expires).toUTCString(); if (typeof option.domain != 'undefined' && option.domain != '' ) buffer += '; domain=' + option.domain; if (typeof option.path != 'undefined' && option.path != '' ) buffer += '; path=' + option.path; if (typeof option.secure == 'boolean' && option.secure ) buffer += '; secure'; document.cookie = buffer + ";"; printf( "<b>Write Cookie</b>:" + buffer); } else { printf( "<b>ERROR:</b>nameあるいはvalueが空です。" ); } } }; //--> </script> </head> <body> <form action="" id="form" name="settings"> <label>name:<input type="text" name="name" id="name" /></label> <label>value:<input type="text" name="value" id="value" /></label> <label>expires:<input type="text" name="expires" id="expires" /></label> <label>domain:<input type="text" name="domain" id="domain" /></label> <label>path:<input type="text" name="path" id="path" /></label> <label><input type="checkbox" name="secure" id="" class="secure" value="true" />secure</label> </form><!-- /#form --> <button onclick=" Cookie.set( settings.name.value, settings.value.value, { expires : settings.expires.value, domain : settings.domain.value, path : settings.path.value, secure : settings.secure.checked } );">Write</button> <button onclick="Cookie.get( settings.name.value );">Load</button> <div id="out"></div><!-- /#console --> </body> </html>