Creation and Retrieval of Cookies in JavaScript
Cookies are a mechanism for storing key-value pairs in a browser's memory. They are commonly used to maintain session information, user preferences, and other data that needs to persist between page refreshes.
In JavaScript, the process of creating and retrieving cookies is straightforward.
Creating a Cookie:
function createCookie(name, value, days) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; }
Retrieving a Cookie:
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 ""; }
To use these functions, simply pass in the desired cookie name, value, and expiry duration (in days) to createCookie(). To retrieve a cookie, pass in its name to getCookie().
The above is the detailed content of How Do I Create and Retrieve Cookies Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!