Detailed Explanation and Example of javascript Operation cookies

  • 2021-07-22 09:03:28
  • OfStack

javascript Operation cookies Detailed Explanation

I have used this method of operating cookies for a long time. But I didn't encounter any problems from 1 to 1. Today, I am doing one. I saved cookies on the first page. Among the functions obtained on the second page or the third page, The limitations of the method are found. For example, the first page path is http://xxxxx/cyb-car2016/h5OfficeWorker/index, and the second page path is http://xxxxx/cyb-car2016/h5AlertController/index. In addition to the domain name, there is a namespace with different types, and cookies is saved under the current page by default, so cookies is saved in the first page. The solution is to set path, document. cookie = name + "=" + escape (value) + "under 1 when saving cookies; expires= "+ exp. toGMTString () +"; path=/"; Where path=/ means that it is saved under the domain name path and available globally


/*********************** Operation cookies Method of ***************************/
// Write cookies 
// This is a usage example with a set expiration time:  
//s20 Is a representative 20 Seconds  
//h Refers to hours, such as 12 Hours are: h12 
//d Is the number of days, 30 Tianze: d30 
function setCookie(name,value,time){
 var strsec = getsec(time); 
 var exp = new Date(); 
 exp.setTime(exp.getTime() + strsec*1); 
 document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/"; 
}

// Read cookies 
function getCookie(name){
 var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");

 if(arr=document.cookie.match(reg)) 
  return unescape(arr[2]); 
 else 
  return false; 
}

//  Delete cookies
function delCookie(name){
 var exp = new Date();
 exp.setTime(exp.getTime() - 1);
 var cval=getCookie(name);
 if(cval!=null)
 document.cookie= name + "="+cval+";expires="+exp.toGMTString()+";path=/";
}

function getsec(str){
 //alert(str); 
 var str1=str.substring(1,str.length)*1; 
 var str2=str.substring(0,1); 
 if (str2=="s")
 { 
  return str1*1000; 
 }
 else if (str2=="h")
 { 
  return str1*60*60*1000; 
 }
 else if (str2=="d")
  { 
   return str1*24*60*60*1000; 
  } 
}


// Get Cookie
//var name = getCookie("name");
//var phone = getCookie("phone");
//
//if(phone != ""){
// $("input[name=phone]").val(phone);
//}
//if(name!="false"){
// $("input[name=name]").val(name);
//}

/*********************** Operation cookies Method of ***************************/


Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: