js cookie使用方法詳解

來源:互聯網
上載者:User
 代碼如下 複製代碼


<script>
function getCookie(c_name){
    if (document.cookie.length>0){  //先查詢cookie是否為空白,為空白就return ""
      c_start=document.cookie.indexOf(c_name + "=")  //通過String對象的indexOf()來

檢查這個cookie是否存在,不存在就為 -1  
      if (c_start!=-1){
        c_start=c_start + c_name.length+1  //最後這個+1其實就是表示"="號啦,這樣

就擷取到了cookie值的開始位置
        c_end=document.cookie.indexOf(";",c_start)  //其實我剛看見indexOf()第二個

參數的時候猛然有點暈,後來想起來表示指定的開始索引的位置...這句是為了得到值的結束位置。因為

需要考慮是否是最後一項,所以通過";"號是否存在來判斷
        if (c_end==-1) c_end=document.cookie.length  
        return unescape(document.cookie.substring(c_start,c_end))  //通過

substring()得到了值。想瞭解unescape()得Crowdsourced Security Testing道escape()是做什麼的,都是很重要的基礎,想瞭解的

可以搜尋下,在文章結尾處也會進行講解cookie編碼細節
      }
    }
    return ""
}  


function setCookie(c_name, value, expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie=c_name+ "=" + escape(value) + "path=/;domain=111cn.net" +

((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}


function sc(days)
{
 setCookie('ashow','a',days);
 document.getElementById('ad').style.display='none';
}

function gc()
{
 if(getCookie('ashow')==1)
 {
  alert(getCookie('ashow'));
  document.getElementById('ad').style.display='none';
 }
}


</script>

<div id="ad">fdsafdsafdsafsda</div>
<script>
gc();
</script>
<a href="#" onclick="javascript:sc(1);">設定Cookie值</a>
<a href="#" onclick="javascript:gc();">擷取Cookie值</a>
<a href="#" onclick="javascript:sc(-1);">清除Cookie值</a>


自己調用 cookie的總結

path= 這個如果你沒有設定那麼你的cookie只能適用於目前的目錄,如

http://www.111cn.net/php/phper.html如果我們在其它頁面如http://www.111cn.net/sj/ 這樣就擷取

不到這個目錄cookie值了

設定方法

path=/ 即可。

domain= 這個是設定網域名稱了,如 我們設定的是www.111cn.net網域名稱,沒設定我們只能在這個網域名稱,那麼

次層網域就是無法讀取cookie值了。

設定

domain=111cn.net

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.