在實現驗證或其他狀態保存中,我不喜歡使用Session,因為在我認為經常會丟失數據,而且SessionID也是基於Cookie來保存的。最近幾天我做了個多語言的小軟件,使用Cookie來保存當前用戶選擇的Cookie,使用jQuery.Cookie插件來設置,對於這個Cookie得path搞得一塌糊塗。在這里記錄一下我對此的理解,問題也能夠得到相應的解決。
1.Path
在.NET中Cookie的的保存獲取就不需要多說了,百度一下基本很多,而且都可以使用,就是這個Path以前一直沒有注意的問題。這個Path描述為虛擬目錄,Cookie允許不同目錄下的值各自獨立。如果沒有指定這個Path,默認就是當前虛擬路徑,這樣就會造成了,設置語言的時候,不同路徑下的語言沒能夠同步解決。其實解決的問題很簡單,將Path設置為根目錄即可,就是“/”。當然如果在當前目錄下設置同樣的鍵的Cookie,將覆蓋根目錄的Cookie,因為當前目錄下的Cookie比較優先。
2.Domain
如果想解決子域名同樣適用這個Cookie,那就可以將Domain設置為域名地址,那樣相同域名下的二級,三級等域名將共享這個Cookie,當然上面提到的Path也需要設置相同的目錄,否則是得不到的。在驗證用戶保存狀態中一般設置為個目錄即“/”,這個目錄是整站公用的目錄,所以在相同站點下的所有目錄的這個Cookie值都是可以得到的。
3.Expires
過期時間,這個主要設置過期時間的長短,在jQuery中可以有兩種設置方法:如果是數字則表示天數,從建立Cookie算起;如果是時間則表示特定的時間。在.NET中就是時間實例對象,如果需要移除這個Cookie可以將這個時間設置為過去的某一個時間,那樣Cookie就會消失。
4.Secure
是否使用安全SSL進行訪問,即HTTPS。
以下是jQuery.Cookie的使用文檔,基本很簡單順便貼上:
1 /** 2 * Create a cookie with the given name and value and other optional parameters. 3 * 4 * @example $.cookie('the_cookie', 'the_value'); 5 * @desc Set the value of a cookie. 6 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true }); 7 * @desc Create a cookie with all available options. 8 * @example $.cookie('the_cookie', 'the_value'); 9 * @desc Create a session cookie. 10 * @example $.cookie('the_cookie', null); 11 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain 12 * used when the cookie was set. 13 * 14 * @param String name The name of the cookie. 15 * @param String value The value of the cookie. 16 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes. 17 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object. 18 * If a negative value is specified (e.g. a date in the past), the cookie will be deleted. 19 * If set to null or omitted, the cookie will be a session cookie and will not be retained 20 * when the the browser exits. 21 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie). 22 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie). 23 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will 24 * require a secure protocol (like HTTPS). 25 * @type undefined 26 * 27 * @name $.cookie 28 * @cat Plugins/Cookie 29 * @author Klaus Hartl/klaus.hartl@stilbuero.de 30 */ 31 32 /** 33 * Get the value of a cookie with the given name. 34 * 35 * @example $.cookie('the_cookie'); 36 * @desc Get the value of a cookie. 37 * 38 * @param String name The name of the cookie. 39 * @return The value of the cookie. 40 * @type String 41 * 42 * @name $.cookie 43 * @cat Plugins/Cookie 44 * @author Klaus Hartl/klaus.hartl@stilbuero.de 45 */
這個Path問題困擾了我好幾天,一不小心想明白了這個問題,所以留下筆記記一下!