Home >Web Front-end >JS Tutorial >JavaScript creates cookies and reads cookies_javascript skills

JavaScript creates cookies and reads cookies_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:07:182089browse

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('郭钱;'); 

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

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);
}

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);

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

Statement:
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