Rumah  >  Artikel  >  hujung hadapan web  >  JS设置获取cookies的方法_javascript技巧

JS设置获取cookies的方法_javascript技巧

WBOY
WBOYasal
2016-05-16 17:02:171308semak imbas

结合JavaScript权威指南,加上项目开发时在网上搜集的资料,整理了两种设置和获取cookie的方法。

复制代码 代码如下:

<script> <P>//设置cookie 方法一<BR>function setCookie(name,value){ <BR>  var exp = new Date(); <BR>  exp.setTime(exp.getTime() + 1*60*60*1000);//有效期1小时 <BR>  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString(); <BR>} <P>/*存取cookie时一般要对容易注入的字符进行编码,相应的在获取cookie时要解码,编码方式有很多种,有时间的话写一篇关于编码解码的博客*/ <P>//设置cookie 方法 二 直接存储cookie<BR>document.cookie = "homepage = http://www.jb51.net"; <P> /*-------------------------------------------------------------------------------------------------------*/ <P>//取cookies函数 方法 一<BR>function getCookie(name){ <P>  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)")); <P>  if(arr != null)     <P>    return unescape(arr[2]); <P>  return null; <P>} <P>//取cookies函数 方法二<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>    return null;<BR>  }<BR>  return null;<BR>} <P></script>

在学习的时候很多js的方法遇到不会的就在网上找资料,直到掌握为止。
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn