Combined with the authoritative JavaScript guide and the information collected online during project development, two methods of setting and obtaining cookies have been compiled.
<script>
<p>//Set cookie Method 1<br>function setCookie(name,value){ <br> var exp = new Date(); <br> exp.setTime(exp.getTime() 1*60*60*1000 );//Validity period is 1 hour<br> document.cookie = name "=" escape (value) ";expires=" exp.toGMTString(); <br>}</p>
<p>/*When accessing cookies, you generally need to encode characters that are easy to inject. Correspondingly, you need to decode when obtaining cookies. There are many encoding methods. If you have time, write a blog about encoding and decoding*/</p>
<p>//Set cookie method 2 Directly store cookies<br>document.cookie = "homepage = http://www.jb51.net";</p>
<p> /*------------------------------------------------ -------------------------------------------------- --------*/</p>
<p>//Get cookies function Method 1<br>function getCookie(name){</p>
<p> var arr = document.cookie.match(new RegExp("(^| )" name "=([^;]*)(;|$)"));</p>
<p>if(arr != null) </p>
<p> return unescape(arr[2]);</p>
<p> return null;</p>
<p>}</p>
<p>//Get cookies function Method 2<br>function getCookie(key){<br>if(key==null)<br> return null;<br>if(Object.prototype.toString.call(key) =='[object String]'|| Object.prototype.toString.call(key)=='[object Number]')<br> {<br> var arrStr = document.cookie.split(";"); <br> for(var i= 0;i<arrStr.length;i ){<BR> var temp = arrStr[i].split("=");<BR> if(temp[0]==key) <BR> return unescape(temp[1]);<BR>
<BR></script>
When I was learning a lot of js methods that I didn’t know, I looked for information online until I mastered them.