如何创build和读取来自cookie的值?

如何在JavaScript中创build和读取cookie中的值?

以下是可用于创build和检索Cookie的function。

var createCookie = function(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=/"; } 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 ""; } 

JQuery Cookies

或纯Javascript:

  function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : ("; expires="+exdate.toUTCString())); document.cookie=c_name + "=" + c_value; } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } 

简约和全function的ES6方法:

 const setCookie = (name, value, days = 7, path = '/') => { const expires = new Date(Date.now() + days * 864e5).toUTCString() document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=' + path } const getCookie = (name) => { return document.cookie.split('; ').reduce((r, v) => { const parts = v.split('=') return parts[0] === name ? decodeURIComponent(parts[1]) : r }, '') } const deleteCookie = (name, path) => { setCookie(name, '', -1, path) } 

Mozilla提供了一个简单的框架来读取和写入完整的Unicode支持的cookies以及如何使用它的例子。

一旦包含在页面中,您可以设置一个cookie:

 docCookies.setItem(name, value); 

阅读一个cookie:

 docCookies.getItem(name); 

或删除一个cookie:

 docCookies.removeItem(name); 

例如:

 // sets a cookie called 'myCookie' with value 'Chocolate Chip' docCookies.setItem('myCookie', 'Chocolate Chip'); // reads the value of a cookie called 'myCookie' and assigns to variable var myCookie = docCookies.getItem('myCookie'); // removes the cookie called 'myCookie' docCookies.removeItem('myCookie'); 

查看Mozilla的document.cookie页面的更多示例和详细信息。

对于那些需要像{foo:'bar'}这样的保存对象的人,我可以分享我编辑过的@ KevinBurke的答案。 我已经添加了JSON.stringify和JSON.parse,就是这样。

 cookie = { set: function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else var expires = ""; document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/"; }, get : function(name){ var nameEQ = name + "=", ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return JSON.parse(c.substring(nameEQ.length,c.length)); } return null; } } 

所以,现在你可以做这样的事情:

 cookie.set('cookie_key', {foo: 'bar'}, 30); cookie.get('cookie_key'); // {foo: 'bar'} cookie.set('cookie_key', 'baz', 30); cookie.get('cookie_key'); // 'baz' 

我已经多次使用这个线程的接受的答案。 这是一个伟大的代码:简单和可用。 但是,我通常使用babel和ES6和模块,所以如果你像我一样,这里是代码复制,以更快的发展与ES6

接受的答案改写为模块与ES6:

 export const createCookie = ({name, value, days}) => { let expires; if (days) { let date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toGMTString(); } else { expires = ''; } document.cookie = name + '=' + value + expires + '; path=/'; }; export const getCookie = ({name}) => { if (document.cookie.length > 0) { let c_start = document.cookie.indexOf(name + '='); if (c_start !== -1) { c_start = c_start + name.length + 1; let 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 ''; }; 

在此之后,您可以简单地导入它作为任何模块(当然path可能会有所不同):

 import {createCookie, getCookie} from './../helpers/Cookie'; 

以下是在JavaScript中获取,设置和删除Cookie的代码。

 function getCookie(name) { name = name + "="; var cookies = document.cookie.split(';'); for(var i = 0; i <cookies.length; i++) { var cookie = cookies[i]; while (cookie.charAt(0)==' ') { cookie = cookie.substring(1); } if (cookie.indexOf(name) == 0) { return cookie.substring(name.length,cookie.length); } } return ""; } function setCookie(name, value, expirydays) { var d = new Date(); d.setTime(d.getTime() + (expirydays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = name + "=" + value + "; " + expires; } function deleteCookie(name){ setCookie(name,"",-1); } 

我使用这个对象。 值被编码,所以当从服务器端读取或写入时需要考虑它。

 cookie = (function() { /** * Sets a cookie value. seconds parameter is optional */ var set = function(name, value, seconds) { var expires = seconds ? '; expires=' + new Date(new Date().getTime() + seconds * 1000).toGMTString() : ''; document.cookie = name + '=' + encodeURIComponent(value) + expires + '; path=/'; }; var map = function() { var map = {}; var kvs = document.cookie.split('; '); for (var i = 0; i < kvs.length; i++) { var kv = kvs[i].split('='); map[kv[0]] = decodeURIComponent(kv[1]); } return map; }; var get = function(name) { return map()[name]; }; var remove = function(name) { set(name, '', -1); }; return { set: set, get: get, remove: remove, map: map }; })(); 

我必须补充,因为惊人的达斯汀·迪亚兹把他列为他所有时间定制的JSfunction。 这是他build议的获取,设置和删除cookies:

 function getCookie(name) { var start = document.cookie.indexOf(name + "="); var len = start + name.length + 1; if ((!start) && (name != document.cookie.substring(0, name.length))) { return null; } if (start == -1) return null; var end = document.cookie.indexOf(';', len); if (end == -1) end = document.cookie.length; return unescape(document.cookie.substring(len, end)); } function setCookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); if (expires) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date(today.getTime() + (expires)); document.cookie = name + '=' + escape(value) + ((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString() ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ((secure) ? ';secure' : ''); } function deleteCookie(name, path, domain) { if (getCookie(name)) document.cookie = name + '=' + ((path) ? ';path=' + path : '') + ((domain) ? ';domain=' + domain : '') + ';expires=Thu, 01-Jan-1970 00:00:01 GMT'; } 

简单的方法来读取ES6中的cookie。

 function getCookies() { var cookies = {}; for (let cookie of document.cookie.split('; ')) { let [name, value] = cookie.split("="); cookies[name] = decodeURIComponent(value); } console.dir(cookies); } 

readCookie的改进版本:

 function readCookie( name ) { var cookieParts = document.cookie.split( ';' ) , i = 0 , part , part_data , value ; while( part = cookieParts[ i++ ] ) { part_data = part.split( '=' ); if ( part_data.shift().replace(/\s/, '' ) === name ) { value = part_data.shift(); break; } } return value; } 

只要你find你的cookie值并返回它的值,这应该会中断。 在我看来,与双重分裂非常优雅。

if条件下的replace是一个白色空间修剪,以确保它匹配正确

 function setCookie(cname,cvalue,exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires=" + d.toGMTString(); document.cookie = cname+"="+cvalue+"; "+expires; } function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } function checkCookie() { var user=getCookie("username"); if (user != "") { alert("Welcome again " + user); } else { user = prompt("Please enter your name:",""); if (user != "" && user != null) { setCookie("username", user, 30); } } } 

我用js-cookie来成功。

 <script src="/path/to/js.cookie.js"></script> <script> Cookies.set('foo', 'bar'); Cookies.get('foo'); </script>