This article mainly introduces how to create and read cookies in javascript. The content is easy to learn. Interested friends can refer to the content in this article, describes how to create a cookie in javascript and how to read a cookie in javascript. The details are as follows:
1. Create a Cookie
Document. cookie = 'key = value ';
Special characters are encoded using encodeURIComponent ().
Document. cookie = 'user = '+ encodeURIComponent ('Guo Qian ;');
Use decodeURIComponent () for reading ()
For example:
Document. cookie = 'name = guoqian '; document. cookie = 'Age = 24'; document. cookie = 'address = hunanc'; document. cookie = 'user = '+ encodeURIComponent ('Guo Qian ;');
Customize a cookie Creation Method
function SetCookie(name, value, expires, path, domain, secure) { var today = new Date(); today.setTime(today.getTime()); if(expires) { expires *= 86400000; } var expires_date = new Date(today.getTime() + (expires)); document.cookie = name + "=" + escape(value) + (expires ? ";expires=" + expires_date.toGMTString() : "") + (path ? ";path=" + path : "") + (domain ? ";domain=" + domain : "") + (secure ? ";secure" : "");}
Ii. obtain cookies
Use string
function getCookieByString(cookieName){ var start = document.cookie.indexOf(cookieName+'='); if (start == -1) return false; start = start+cookieName.length+1; var end = document.cookie.indexOf(';', start); if (end == -1) end=document.cookie.length; return document.cookie.substring(start, end);}
Array
Function getCookieByArray (name) {var cookies = document. cookie. split (';'); var c; for (var I = 0; I
The above is all the content of this article, hoping to help you learn.