簡體   English   中英

無法在路徑/下訪問javascript中的cookie

[英]Not able to access cookie in javascript at path /

我正在使用jQuery訪問/設置cookie。 我在路徑/處植入了一個名為CookieNo1的cookie。

我使用url localhost:8080/audi種植了它。

cookie值已存儲,我在Firefox cookie上手動檢查過。 現在,當我嘗試訪問相同的cookie時,使用$.cookie('CookieNo1');使用url localhost:8080/audi/products $.cookie('CookieNo1');

這似乎沒有檢索cookie的值。 它返回一個空值。 但是,當我嘗試使用相同的localhost:8080/audi/products url編寫cookie時,它將覆蓋以前的cookie值。 請幫我解決這個問題。

我需要的只是$.cookie('CookieNo1')返回以前的cookie值,而不是null。 提前致謝

您必須設置有效期限。 否則,cookie將在會話結束時被刪除。 在JQuery中: $("CookieNo1", "value", {expires: 7}) (此cookie保留7天)。

在JavaScript中:

document.cookie = "CookieNo1=value; max-age=604800";

max-age設置cookie的最長生存時間(以秒為單位)。

編輯

引用評論:

@RobW我在頁面http:// localhost:8080 / audi上使用jquery添加了cookie,其代碼$.cookie("asdftraffic", valueToSet, { expires: 30, path: '/', secure: true }); 我嘗試使用'$.cookie('asdftraffic');'從URL http:// localhost:8080 / audi / products檢索cookie '$.cookie('asdftraffic');' 返回null。

您的問題是由secure: true引起的secure: true 此屬性要求cookie通過安全連接( https )傳輸。 如果您不使用加密連接,請刪除secure: true標志。

首先,您設置cookie:

var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue);

然后,您獲得cookie:

var getmycookie = $.cookie("mycookie");
    var myvalues = getmycookie.split(",");
    var firstval = myvalues[0];
    var secondval = myvalues[1];
    var thirdval = myvalues[2];

應該不難得多。 如果未指定到期時間,則在會話結束時即關閉瀏覽器時刪除cookie。

編輯:您還可以指定路徑:

$.cookie("mycookie", myvalue, {
expires : 10,           //expires in 10 days

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

domain  : 'http://localhost:8080',  //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).
});

我認為這樣可以:

var myvalue = 100, 2000, 300;
$.cookie("mycookie", myvalue, {path : '/audi/products'});

哦,會話會在關閉瀏覽器時結束,而不是在頁面卸載時結束,因此會話cookie會完成。

暫無
暫無

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

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