Last weekend, I had a job interview with regards to Javascript. I was asked if Javascript can pass values from one page to another. All I said was if it is possible, I can look it up in Google. When my initial exam started, I looked it up if it is indeed possible. And voila, cookies were mentioned. I have never used cookies in Javascript before so I totally had no idea until I looked it up. The best functions for me in setting and retrieving cookies in Javascript are the functions found in a W3Schools column.
Using these two functions below, you can set and get a cookie (depending on the expiry value you specify).
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
function setCookie(c_name, value, expiredays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + expiredays); document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString()); } function getCookie(c_name) { if (document.cookie.length > 0) { c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end == -1) c_end = document.cookie.length; return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } |
yeah.. nice tutor. 🙂