Home  >  Article  >  Web Front-end  >  Detailed explanation of method examples for setting cookies in javascript

Detailed explanation of method examples for setting cookies in javascript

伊谢尔伦
伊谢尔伦Original
2017-07-22 13:56:401161browse

The use of js to set cookies

php can set cookies. What are the benefits of using js to set cookies? When operating on the front end, sometimes a lot of parameters need to be passed. At this time, we can splice these parameters to the back of the URL and pass the values. The parameters are received there, but this is quite troublesome. If we put these data in the cookie , in terms of the development efficiency of developers, it will be higher. Take Taobao as an example. It has first-level classification, second-level classification, third-level, and fourth-level. When we are looking for products, there may be many conditions involved. If we combine these It feels much more convenient to put all the conditions in the cookie. I don’t know if Taobao is like this. Taobao's URL is encrypted and very long. It may be that it is rooted at the back of the URL. Without further ado, let’s look at a small example.

Example


##

//取得cookie
function getCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';'); //把cookie分割成组
 for(var i=0;i < ca.length;i++) {
 var c = ca[i]; //取得字符串
 while (c.charAt(0)==&#39; &#39;) { //判断一下字符串有没有前导空格
 c = c.substring(1,c.length); //有的话,从第二位开始取
 }
 if (c.indexOf(nameEQ) == 0) { //如果含有我们要的name
 return unescape(c.substring(nameEQ.length,c.length)); //解码并截取我们要值
 }
 }
 return false;
}
//清除cookie
function clearCookie(name) {
 setCookie(name, "", -1);
}
//设置cookie
function setCookie(name, value, seconds) {
 seconds = seconds || 0; //seconds有值就直接赋值,没有为0,这个根php不一样。
 var expires = "";
 if (seconds != 0 ) { //设置cookie生存时间
 var date = new Date();
 date.setTime(date.getTime()+(seconds*1000));
 expires = "; expires="+date.toGMTString();
 }
 document.cookie = name+"="+escape(value)+expires+"; path=/"; //转码并赋值
}

Call the above method:


setCookie("test","tank",1800); //设置cookie的值,生存时间半个小时
alert(getCookie(&#39;test&#39;)); //取得cookie的值,显示tank
clearCookie("test"); //删除cookie的值
alert(getCookie(&#39;test&#39;)); //test对应的cookie值为空,显示为false.就是getCookie最后返的false值。

The above is the detailed content of Detailed explanation of method examples for setting cookies in javascript. For more information, please follow other related articles on the PHP Chinese website!

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