JS设置获取cookies的方法

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

  

复制代码 代码如下:

  <script>

  //设置cookie  方法一

  function setCookie(name,value){

  var exp = new Date();

  exp.setTime(exp.getTime() + 1*60*60*1000);//有效期1小时

  document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();

  }

  /*存取cookie时一般要对容易注入的字符进行编码,相应的在获取cookie时要解码,编码方式有很多种,有时间的话写一篇关于编码解码的博客*/

  //设置cookie 方法 二 直接存储cookie

  document.cookie = "homepage = http://www.glzy8.com";

  /*-------------------------------------------------------------------------------------------------------*/

  //取cookies函数 方法 一

  function getCookie(name){

  var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));

  if(arr != null)    

    return unescape(arr[2]);

  return null;

  }

  //取cookies函数  方法二

  function getCookie(key){

  if(key==null)

    return null;

  if(Object.prototype.toString.call(key)=='[object String]'|| Object.prototype.toString.call(key)=='[object Number]')

  {

    var arrStr = document.cookie.split(";");

    for(var i= 0;i<arrStr.length;i++){

    var temp = arrStr[i].split("=");

    if(temp[0]==key)

      return unescape(temp[1]);

    }

    return null;

  }

  return null;

  }

  </script>

  在学习的时候很多js的方法遇到不会的就在网上找资料,直到掌握为止。