Home > Web Front-end > JS Tutorial > How to set, get and delete cookies in javascript_javascript skills

How to set, get and delete cookies in javascript_javascript skills

WBOY
Release: 2016-05-16 15:57:06
Original
1012 people have browsed it

The example in this article describes the method of setting, obtaining and deleting cookies in javascript. Share it with everyone for your reference. The specific implementation method is as follows:

/* 
 *设置Cookie 
 * 
 * name:cookie所对应的键 
 * value:cookie所对应的值 
 * expires:cookie所对应的有效时间 
 * path:指定可访问cookie的路径 
 * domain:指定可访问cookie的主机名 
 * secure:安全性 
 */ 
function setCookie (name,value,expires,path,domain,secure) {   
  //cookie键值对  
  var str = name + "=" + escape(value); 
  //设置cookie的有效期,以小时为单位 
  if(expires > 0){                 
    var date = new Date(); 
    var ms = expires * 3600 * 1000; 
    date.setTime(date.getTime() + ms); 
    str += "; expires=" + date.toGMTString(); 
  } 
  if(path){ 
    str += "; path=" + path; 
  } 
  if(domain){ 
    str += "; domain=" + domain; 
  } 
  if(secure){ 
    str += "; secure"; 
  } 
  document.cookie = str; 
} 
/* 
 *获得Cookie 
 * 
 *cookie_name:cookie的键 
 */ 
function getCookie(cookie_name)  
{    
  var value = null; 
  var allcookies = document.cookie;  
  var cookie_pos = allcookies.indexOf(cookie_name);  
  // 如果找到了索引,就代表cookie存在,  
  // 反之,就说明不存在。  
  if (cookie_pos != -1)  
  {  
    // 把cookie_pos放在值的开始,只要给值加1即可。  
    cookie_pos += cookie_name.length + 1;  
    var cookie_end = allcookies.indexOf(";", cookie_pos);  
    if (cookie_end == -1)  
    {   
      cookie_end = allcookies.length;  
    }  
    value = unescape(allcookies.substring(cookie_pos, cookie_end));  
  }  
  return value;  
}  
/* 
 *删除Cookie 
 * 
 *cookie_name:cookie的键 
 */ 
function delCookie(cookie_name) 
{ 
  var exp = new Date(); 
  exp.setTime(exp.getTime() - 1); 
  var value = getCookie(cookie_name); 
  if(value){ 
    document.cookie= cookie_name + "=" + value + ";expires=" + exp.toGMTString(); 
  } 
}

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
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