2011-10-01 134 views
1

我使用jQuery來訪問/設置cookie。我在路徑/上種植了一個名爲CookieNo1的cookie。無法在javascript中訪問cookie路徑/

我種植這個使用的網址localhost:8080/audi

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

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

我需要的是$.cookie('CookieNo1')返回以前的cookie值而不是null。 在此先感謝

+0

你使用jQuery嗎? –

+0

@Maxim這是一個cookie問題。網址路徑沒有問題,因爲您可能已經想到了,因爲cookie是按域存儲的,並且會針對源自該域的任何請求發送每個請求。您可以檢查「document.cookie」在此網址上返回的http :// localhost:8080/audi/products' – Deeptechtons

+0

@BookOfZeus是的,我正在使用jquery,在這個問題中也加入了這個問題 –

回答

4

您必須設置到期日期。否則,該cookie在會話結束時被刪除。在JQuery中:$("CookieNo1", "value", {expires: 7})(這個cookie保留7天)。

在JavaScript:

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

max-age設置一個cookie的最大壽命,單位爲秒。

編輯

從意見報價:

@RobW我使用頁面 http://localhost:8080/audi的代碼$.cookie("asdftraffic", valueToSet, { expires: 30, path: '/', secure: true });我嘗試 jQuery的加入餅乾使用'$.cookie('asdftraffic');'網址http://localhost:8080/audi/products 獲取餅乾它返回null。

您的問題是由secure: true造成的。此屬性要求Cookie通過安全連接進行傳輸(https)。如果您未使用加密連接,請刪除secure: true標誌。

+0

這不是我要找的。我想訪問Cookie路徑/從URL本地主機:8080 /奧迪/產品 –

+0

@MaximDsouza COL,餅乾保存每個域是'http:// localhost:8080'和'http:// localhost:8080 /奧迪/產品'看起來像你不同的領域? – Deeptechtons

+0

@Deeptechtons我什麼時候說他們是不同的領域。它們位於同一個域中,但由/ audi url種植的cookie不能在/ audi/products url上訪問。 –

1

首先你設置Cookie:

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

然後你得到的餅乾:

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

Should'nt更難。 當未指定過期時,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將會執行。

+0

'var getmycookie = $ .cookie(「mycookie」);'當從http:// localhost:8080/audi/products'訪問時,我返回null,當cookie使用http:// localhost :8080/audi' –