Home > Web Front-end > JS Tutorial > body text

JavaScript creates cookies and reads cookies_javascript skills

WBOY
Release: 2016-05-16 15:07:18
Original
2039 people have browsed it

The content of this article is divided into two parts for learning. They introduce the specific implementation methods of creating cookies with javascript and reading cookies with javascript for everyone to learn. The specific content is as follows

1. Create Cookie

document.cookie = 'key=value';

If there are special characters, use encodeURIComponent() to encode

document.cookie = 'user='+encodeURIComponent('Guo Qian;');

Use decodeURIComponent()

when reading

For example:

document.cookie = 'name=guoqian';
document.cookie = 'age=24';
document.cookie = 'address=hunan';
document.cookie = 'user='+encodeURIComponent('郭钱;'); 
Copy after login

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" : "");
}
Copy after login

2. Obtain cookie

Use string method

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);
}
Copy after login

Use array method

function getCookieByArray(name){
 var cookies = document.cookie.split(';');
 var c;
 for(var i=0; i<cookies.length ; i++){
  c = cookies[i].split('=');
  if (c[0].replace(' ', '') == name) {
   return c[1];
  }
 }
}
var r = decodeURIComponent(getCookieByArray('user'));
alert(r);
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template