This time I will show you how to set cookies in the front-end, and what are the precautions for setting cookies in the front-end. The following is a practical case, let's take a look.
What it is: It is a means of storing information on the client's hard drive.Why use? : Can be used to store some information and achieve some special effects. For example, you can avoid logging in for a certain number of days, or store some small data.
The meaning of some fields in cookie:
key=value (key=value) is a key-value pair of cookie, usually obtained based on key The corresponding value
expires (expiration time) sets the expiration time of the cookie, also separated by ';', expires=GMT timeString, For example, if you want to avoid logging in for 30 days, you can set the expiration date to a date 30 days from today. If the expiration time is not set, the browser will close the cookie and disappear by default.
path (path) cookie cannot be obtained everywhere. The website is divided into many directories. Cookies may not be used in many directories, so you can set the cookie path, which is more secure and prevents any directory from accessing the cookie. Pass path=/E:javascript/test so that the cookie can only be obtained in this directory
Note: It is not allowed to directly assign values to cookies by opening local HTML files on Google browser, but Firefox can. So if you want to test, first open a local server and then use the local IP to access the file. Perform cookie operations. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese websitedocument.cookie; //获取cookie "aaa=aaa;bbb=bbb" //类似于这种格式,但是并不是字符串。 //设置cookie,也可以用来进行删除cookie,即将过期时间设置为过去的时间,最后一个参数可以传负数来实现 function setCookie(cname,cvalue,exdays){ var d = new Date(); d.setTime(d.getTime()+(exdays*24*60*60*1000)); var expires = "expires="+d.toGMTString(); document.cookie = cname + "=" + cvalue + "; " + expires; } setCookie('cjs','cjs',30); //设置 name为cjs,value为cjs的一个cookie,并且时间为30天。 setCookie('cjs','cjs',-1); //让该cookie过期,然后在document.cookie中就没有cjs=cjs这个cookie了。但是其他key=value还存在 //获取某个key的cookie function getCookie(key){ let arr1 = document.cookie.split(';'); for(let i=0;i<arr1.length;i++){ let arr2 = arr1[i].split('='); if(key.trim() === arr2[0].trim()){ return (arr2[1]); } } return ""; } getCookie('cjs'); //因为上面已经将cjs这个cookie干掉了,所以这里得到为 ""Copy after login
Other related articles!
Recommended reading:Use CSS to realize table tennis fighting animation
Use CSS to realize table tennis fighting animation
The above is the detailed content of How to set cookies in the front end. For more information, please follow other related articles on the PHP Chinese website!