Home > Web Front-end > JS Tutorial > JS settings method to obtain cookies_javascript skills

JS settings method to obtain cookies_javascript skills

WBOY
Release: 2016-05-16 17:02:17
Original
1336 people have browsed it

Combined with the authoritative JavaScript guide and the information collected online during project development, two methods of setting and obtaining cookies have been compiled.

Copy code The code is as follows:

<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.

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