2015-09-06 25 views
-1

我是JavaScript和cookies的新手,所以我有這個奇怪的問題,因爲不同的網站有不同的格式。所以我對cookies如何讀取和訪問它的不同部分感到困惑,即Cookie如何識別路徑或到期日期中的名稱?我們是否總是需要指定「username = ...; path = /;」爲了識別它,還是根據格式自動找到它? 我想要解決的主要問題是如何向cookie創建代碼添加值,例如「document.cookie =」username = John; visit = 1;「並使用該訪問部分來告訴擊中每次加1,它的頁面加載計數餅乾如何識別名稱,過期日期,路徑

謝謝!

回答

1

我用兩個函數(也許原來的代碼是從herehere)用於獲取和設置的cookie,這裏有他們:

function setCookie(cookieName, content, expires, path) { 
    var date = new Date(); 
    date.setDate(date.getDate() + expires); 
    var cookie = escape(content) + (expires == null ? "" : "; expires=" + date.toUTCString()) + (path != null ? "; path=" + path : ""); 
    document.cookie = cookieName + "=" + cookie; 
    return true; 
} 

function getCookie(cookieName) { 
    var cookie = document.cookie, 
     begin = cookie.indexOf(" " + cookieName + "="); 
    if (begin == -1) begin = cookie.indexOf(cookieName + "="); 
    if (begin == -1) cookie = null; 
    else { 
    begin = cookie.indexOf("=", begin) + 1; 
    var end = cookie.indexOf(";", begin); 
    if (end == -1) end = cookie.length; 
    cookie = unescape(cookie.substring(begin, end)); 
    } 
    return cookie; 
} 

隨着他們你可以輕鬆地做你想做的事情T:

  1. 處理頁面負載(例如<body onload="pageLoad()">
  2. 添加腳本元件到頁的頭部部分,以及兩個funtions上述
  3. 添加腳本元件內的以下功能:
    function pageLoad() { var cCont = getCookie('hitCount'); var count = 0; if (cCont != null) count = parseInt(count + ''); setCookie('hitCount', (count + 1) + '', null, null); }
  4. 如果你想得到命中計數,你可以使用count變量,或再次使用getCookie函數。


你的第一個問題對我來說還不完全清楚,但是請閱讀this page,這裏有很好的例子和代碼示例。 This是Cookie的另一個很好的介紹。