簡體   English   中英

如何使用 jQuery 設置/取消設置 cookie?

[英]How do I set/unset a cookie with jQuery?

如何使用 jQuery 設置和取消設置 cookie,例如創建一個名為test的 cookie 並將值設置為1

2019 年 4 月更新

cookie 讀取/操作不需要 jQuery,所以不要使用下面的原始答案。

請轉至https://github.com/js-cookie/js-cookie ,並使用不依賴於 jQuery 的庫。

基本示例:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

有關詳細信息,請參閱 github 上的文檔。


2019年4月之前(舊)

查看插件:

https://github.com/carhartl/jquery-cookie

然后你可以這樣做:

$.cookie("test", 1);

刪除:

$.removeCookie("test");

此外,要在 cookie 上設置特定天數(此處為 10 天)的超時:

$.cookie("test", 1, { expires : 10 });

如果省略 expires 選項,則 cookie 將成為會話 cookie,並在瀏覽器退出時被刪除。

要涵蓋所有選項:

$.cookie("test", 1, {
   expires : 10,           // Expires in 10 days

   path    : '/',          // The value of the path attribute of the cookie
                           // (Default: path of page that created the cookie).

   domain  : 'jquery.com', // The value of the domain attribute of the cookie
                           // (Default: domain of page that created the cookie).

   secure  : true          // If set to true the secure attribute of the cookie
                           // will be set and the cookie transmission will
                           // require a secure protocol (defaults to false).
});

要讀回 cookie 的值:

var cookieValue = $.cookie("test");

如果 cookie 是在與當前路徑不同的路徑上創建的,您可能希望指定 path 參數:

var cookieValue = $.cookie("test", { path: '/foo' });

更新(2015 年 4 月):

正如下面的評論中所述,開發原始插件的團隊已經刪除了一個新項目 ( https://github.com/js-cookie/js-cookie ) 中的 jQuery 依賴項,該項目具有相同的功能和通用語法jQuery 版本。 顯然,原始插件不會去任何地方。

不需要特別使用 jQuery 來操作 cookie。

來自QuirksMode (包括轉義字符)

function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = encodeURIComponent(name) + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ')
            c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0)
            return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

看一眼

<script type="text/javascript">
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

</script>

您可以將 cookie 設置為

setCookie('test','1','1'); //(key,value,expiry in days)

你可以像這樣獲得餅干

getCookie('test');

最后你可以像這樣擦除餅干

eraseCookie('test');

希望它會對某人有所幫助:)

編輯:

如果要將 cookie 設置為所有路徑/頁面/目錄,則將路徑屬性設置為 cookie

function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 24 * 60 * 60 * 1000));
        document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
}

謝謝,維琪

您可以使用此處提供的插件..

https://plugins.jquery.com/cookie/

然后寫一個 cookie 做$.cookie("test", 1);

要訪問設置的 cookie,請執行$.cookie("test");

這是我使用的全局模塊 -

var Cookie = {   

   Create: function (name, value, days) {

       var expires = "";

        if (days) {
           var date = new Date();
           date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
           expires = "; expires=" + date.toGMTString();
       }

       document.cookie = name + "=" + value + expires + "; path=/";
   },

   Read: function (name) {

        var nameEQ = name + "=";
        var ca = document.cookie.split(";");

        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == " ") c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }

        return null;
    },

    Erase: function (name) {

        Cookie.create(name, "", -1);
    }

};

確保不要做這樣的事情:

var a = $.cookie("cart").split(",");

然后,如果 cookie 不存在,調試器將返回一些無用的消息,例如“.cookie not a function”。

總是先聲明,然后在檢查 null 后進行拆分。 像這樣:

var a = $.cookie("cart");
if (a != null) {
    var aa = a.split(",");

以下是使用 JavaScript 設置 cookie 的方法:

以下代碼取自https://www.w3schools.com/js/js_cookies.asp

 function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }

現在您可以使用以下功能獲取cookie:

 function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }

最后,這是您檢查 cookie 的方式:

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

如果您想刪除 cookie,只需將 expires 參數設置為傳遞的日期:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

在瀏覽器中設置 cookie 的簡單示例:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jquery.cookie Test Suite</title>

        <script src="jquery-1.9.0.min.js"></script>
        <script src="jquery.cookie.js"></script>
        <script src="JSON-js-master/json.js"></script>
        <script src="JSON-js-master/json_parse.js"></script>
        <script>
            $(function() {

               if ($.cookie('cookieStore')) {
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              }

              $('#submit').on('click', function(){

                    var storeData = new Array();
                    storeData[0] = $('#inputName').val();
                    storeData[1] = $('#inputAddress').val();

                    $.cookie("cookieStore", JSON.stringify(storeData));
                    var data=JSON.parse($.cookie("cookieStore"));
                    $('#name').text(data[0]);
                    $('#address').text(data[1]);
              });
            });

       </script>
    </head>
    <body>
            <label for="inputName">Name</label>
            <br /> 
            <input type="text" id="inputName">
            <br />      
            <br /> 
            <label for="inputAddress">Address</label>
            <br /> 
            <input type="text" id="inputAddress">
            <br />      
            <br />   
            <input type="submit" id="submit" value="Submit" />
            <hr>    
            <p id="name"></p>
            <br />      
            <p id="address"></p>
            <br />
            <hr>  
     </body>
</html>

簡單只需復制/粘貼並使用此代碼來設置您的 cookie。

您可以在此處使用 Mozilla 網站上的庫

您將能夠像這樣設置和獲取 cookie

docCookies.setItem(name, value);
docCookies.getItem(name);

我認為 Fresher 給了我們很好的方式,但有一個錯誤:

    <script type="text/javascript">
        function setCookie(key, value) {
            var expires = new Date();
            expires.setTime(expires.getTime() + (value * 24 * 60 * 60 * 1000));
            document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }
   </script>

您應該在 getTime() 附近添加“值”; 否則cookie將立即過期:)

我認為Vignesh Pichamani的答案是最簡單和最干凈的。 只是增加了他設置到期前天數的能力:

編輯:如果沒有設置天數,還添加了“永不過期”選項

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

設置cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 

我知道有很多很棒的答案。 通常,我只需要讀取 cookie,我不想通過加載額外的庫或定義函數來創建開銷。

以下是如何在一行 javascript 中讀取 cookie 我在Guilherme Rodrigues 的博客文章中找到了答案:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

這會讀取名為key的 cookie,不錯,干凈且簡單。

嘗試(文檔在這里,所以片段不起作用所以運行這個

document.cookie = "test=1"             // set
document.cookie = "test=1;max-age=0"   // unset

以下代碼將刪除當前域中的所有 cookie 和所有尾隨子域( www.some.sub.domain.com.some.sub.domain.com.sub.domain.com等)。

單行香草 JS 版本(不需要 jQuery):

document.cookie.replace(/(?<=^|;).+?(?=\=|;|$)/g, name => location.hostname.split('.').reverse().reduce(domain => (domain=domain.replace(/^\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));

這是這一行的可讀版本:

document.cookie.replace(
  /(?<=^|;).+?(?=\=|;|$)/g, 
  name => location.hostname
    .split(/\.(?=[^\.]+\.)/)
    .reduceRight((acc, val, i, arr) => i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')
    .map(domain => document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)
);

我知道,已經有很多答案了,但這里有一個setgetdelete所有精美的香草,並很好地放入了全局參考:

window.cookieMonster = window.cookieMonster || 
    {
        // https://stackoverflow.com/a/25490531/1028230
        get: function (cookieName) {
            var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
            return b ? b.pop() : '';
        },

        delete: function (name) {
            document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
                .replace('{0}', name);
        },

        set: function (name, value) {
            document.cookie =
                '{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
                .replace('{0}', name)
                .replace('{1}', value);
        }
    };

請注意 cookie 獲取正則表達式是從另一個城堡中的一個問題的答案中獲取的


讓我們測試一下:

cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

cookieMonster.delete('chocolate');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

如果你在嘗試之前沒有任何餅干,應該給你......

yes please
chocolate=yes please; sugar=that too

sugar=that too

請注意,餅干持續的時間並不長,但從我們的角度來看,本質上是這樣。 您可以通過查看此處的字符串或其他答案來輕松了解如何更改日期。

與以前的答案相比,減少了操作次數,我使用以下內容。

function setCookie(name, value, expiry) {
    let d = new Date();
    d.setTime(d.getTime() + (expiry*86400000));
    document.cookie = name + "=" + value + ";" + "expires=" + d.toUTCString() + ";path=/";
}

function getCookie(name) {
    let cookie = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return cookie ? cookie[2] : null;
}

function eatCookie(name) {
    setCookie(name, "", -1);
}
$.cookie("test", 1); //set cookie
$.cookie("test"); //get cookie
$.cookie('test', null); //delete cookie

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM