JS創建和存儲 cookie的一些方法

在js中cookie的操作與存儲及清除cookie都與時間有關,我們只要把cookie過期時間進行有效的設置我們就可以控制它的存儲了,下面我來給大家總結一下js中cookie的一些使用技巧

創建和存儲 cookie

在這個例子中我們要創建一個存儲訪問者名字的 cookie。當訪問者首次訪問網站時,他們會被要求填寫姓名。名字會存儲於 cookie 中。當訪問者再次訪問網站時,他們就會收到歡迎詞。

首先,我們會創建一個可在 cookie 變量中存儲訪問者姓名的函數:

 代碼如下 複製代碼

function Setcookie (name, value)

    //設置名稱爲name,值爲value的Cookie
    var expdate = new Date();   //初始化時間
    expdate.setTime(expdate.getTime() + 30 * 60 * 1000);   //時間
    document.cookie = name+"="+value+";expires="+expdate.toGMTString()+";path=/";

   //即document.cookie= name+"="+value+";path=/";   時間可以不要,但路徑(path)必須要填寫,因爲JS的默認路徑是當前頁,如果不填,此cookie只在當前頁面生效!~
}


上面這個函數中的參數存有 cookie 的名稱、值以及過期天數。

在上面的函數中,我們首先將天數轉換爲有效的日期,然後,我們將 cookie 名稱、值及其過期日期存入 document.cookie 對象。

之後,我們要創建另一個函數來檢查是否已設置 cookie:

 代碼如下 複製代碼

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1 
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    } 
  }
return ""
}

上面的函數首先會檢查 document.cookie 對象中是否存有 cookie。假如 document.cookie 對象存有某些 cookie,那麼會繼續檢查我們指定的 cookie 是否已儲存。如果找到了我們要的 cookie,就返回值,否則返回空字符串。

最後,我們要創建一個函數,這個函數的作用是:如果 cookie 已設置,則顯示歡迎詞,否則顯示提示框來要求用戶輸入名字。

 代碼如下 複製代碼

function checkCookie()
{
username=getCookie('username')
if (username!=null && username!="")
  {alert('Welcome again '+username+'!')}
else 
  {
  username=prompt('Please enter your name:',"")
  if (username!=null && username!="")
    {
    setCookie('username',username,365)
    }
  }
}

     

一個完整實例

 

 代碼如下 複製代碼

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>無標題文檔</title>
<script type=”text/javascript”>
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + “=”)
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(“;”,c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return “”
}

function setCookie(c_name,value,expiredays)
{
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ “=” +escape(value)+
((expiredays==null) ? “” : “;expires=”+exdate.toGMTString())
}

function checkCookie()
{
username=getCookie(‘username’)
if (username!=null && username!=”")
{alert(‘Welcome again ‘+username+’!')}
else
{
username=prompt(‘Please enter your name:’,”")
if (username!=null && username!=”")
{
setCookie(‘username’,username,365)
}
}
}
</script>
</head>
<body onLoad=”checkCookie()”>

</body>
</html>


上面講到了cookie的創建我們現在來看一個利用cookie保存瀏覽記錄實例

瀏覽記錄的顯示是從cookie裏讀出來,然後解析成json,生成html元素。因爲用戶可能會同時打開好幾個頁面,這幾個頁面上可能都有瀏覽記錄,爲了使即使顯示瀏覽記錄,每秒中刷新一次。
要用到2個js文件,history.js,關鍵的聊天記錄保存和讀取代碼。json.js,對json進行處理。

history.js

 代碼如下 複製代碼

var addHistory=function(num,id){
    stringCookie=getCookie('history');
    var stringHistory=""!=stringCookie?stringCookie:"{history:[]}";
    var json=new JSON(stringHistory);
    var e="{num:"+num+",id:"+id+"}";
    json['history'].push(e);//添加一個新的記錄
    setCookie('history',json.toString(),30);
}
//顯示歷史記錄
var DisplayHistory=function(){
    var p_ele=document.getElementById('history');
     while (p_ele.firstChild) {
      p_ele.removeChild(p_ele.firstChild);
     }

    var historyJSON=getCookie('history');
    var json=new JSON(historyJSON);
    var displayNum=6;
    for(i=json['history'].length-1;i>0;i--){
        addLi(json['history'][i]['num'],json['history'][i]['id'],"history");
        displayNum--;
        if(displayNum==0){break;}
    }
}
//添加一個li元素
var addLi=function(num,id,pid){
    var a=document.createElement('a');
    var href='product.action?pid='+id;
    a.setAttribute('href',href);
    var t=document.createTextNode(num);
    a.appendChild(t);
    var li=document.createElement('li');
    li.appendChild(a);
    document.getElementById(pid).appendChild(li);
}
//添加cookie
var setCookie=function(c_name,value,expiredays)
{
    var exdate=new Date()
    exdate.setDate(exdate.getDate()+expiredays)
    cookieVal=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
//    alert(cookieVal);
    document.cookie=cookieVal;
}
//獲取cookie
function getCookie(c_name)
{
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=")
      if (c_start!=-1)
        { 
        c_start=c_start + c_name.length+1 
        c_end=document.cookie.indexOf(";",c_start)
        if (c_end==-1) c_end=document.cookie.length
//        document.write(document.cookie.substring(c_start,c_end)+"<br>");
        return unescape(document.cookie.substring(c_start,c_end))
        } 
      }
    return ""
}

json文件

 代碼如下 複製代碼

json.js 
var JSON = function(sJSON){
    this.objType = (typeof sJSON);
    this.self = [];
    (function(s,o){for(var i in o){o.hasOwnProperty(i)&&(s[i]=o[i],s.self[i]=o[i])};})(this,(this.objType=='string')?eval('0,'+sJSON):sJSON);
}
JSON.prototype = {
    toString:function(){
        return this.getString();
    },
    valueOf:function(){
        return this.getString();
    },
    getString:function(){
        var sA = [];
        (function(o){
            var oo = null;
            sA.push('{');
            for(var i in o){
                if(o.hasOwnProperty(i) && i!='prototype'){
                    oo = o[i];
                    if(oo instanceof Array){
                        sA.push(i+':[');
                        for(var b in oo){
                            if(oo.hasOwnProperty(b) && b!='prototype'){
                                sA.push(oo[b]+',');
                                if(typeof oo[b]=='object') arguments.callee(oo[b]);
                            }
                        }
                        sA.push('],');
                        continue;
                    }else{
                        sA.push(i+':'+oo+',');
                    }
                    if(typeof oo=='object') arguments.callee(oo);
                }
            }
            sA.push('},');
        })(this.self);
        return sA.slice(0).join('').replace(/[object object],/ig,'').replace(/,}/g,'}').replace(/,]/g,']').slice(0,-1);
    },
    push:function(sName,sValue){
        this.self[sName] = sValue;
        this[sName] = sValue;
    }
}

html文檔

 代碼如下 複製代碼

示例程序 
<script type="text/javascript" src="../js/json.js"></script>
<script type="text/javascript" src="../js/history.js"></script>
<ul id="history">
</ul>
<script> 
addHistory(15810782304,2);
addHistory(64654665,2);
addHistory(6843212,2);
addHistory(84984432521,2);
setInterval("DisplayHistory()",1000);
</script>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章