JavaScript設定Cookie寫法
JavaScript設定、刪除Cookie最簡易寫法如下:Set Cookie
dcument.cookie = "name=test";Delete Cookie
dcument.cookie = "name=; expire=Thu, 18 Dec 2013 12:00:00 GMT;";後面的時間只要比現在的時間還前面就可以。
Set Cookie 完整寫法
document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; domain=.example.com; path=/"; document.cookie="username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 GMT; path=/"; // 不寫 domain 簡短寫法
將Cookie設定帶入JavaScript範例程式 設定1天過期,cookie name : name , value : test
expire_days = 1; // 過期日期(天) var d = new Date(); d.setTime(d.getTime() + (expire_days * 24 * 60 * 60 * 1000)); var expires = "expires=" + d.toGMTString(); document.cookie = "name=test" + "; " + expires + '; domain=blog.longwin.com.tw; path=/'; // alert(document.cookie)
刪除Cookie,將cookie name的value清空,並將過期時間設定為現在時間-1即可。
var d = new Date(); d.setTime(d.getTime() -1); var expires = "expires=" + d.toGMTString(); document.cookie = "name=; expires=" + expires + '; domain=blog.longwin.com.tw; path=/'; // alert(document.cookie)
《O'REILLY深入淺出JavaScript》中提到的Cookie,寫出不同的function,readCookie()、writeCookie()、eraseCookie()。
writeCookie()
function writeCookie(name,value,days){ var expires = ""; if (days){ var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 100)); expires = "; expires=" + date.toGMTString(); } document.cookie = name + "=" + value + expires + "; path=/"; }
readCookie()
function readCookie(name) { var searchName = name + "="; var cookies = document.cookie.split(';'); for (var i = 0 ; i < cookie.length ; i++){ var c = cookie[i]; while (c.charAt(0) == ' ') c = c.substring(1,c.length); if (c.indexOf(searchName) == 0) return c.substring(searchName.length, c.length); } return null; }
eraseCookie()
function eraseCookie(name){ writeCookie(name,"",-1); }
寫成function的方式看起來比較清楚,對於別的function可以直接取用,不必再寫繁雜的程式碼。例如:
function greetUser(){ userName = readCookie("irock_username"); if (userName) alert("Hello " + userName + ", Imissed you."); else alert('Hello, I am your pet rock.'); }
實務上是怎麼去運用要等以後才知道。
沒有留言:
張貼留言