如何使用jQuery操作Cookies方法解析
Cookies
定義:讓網站服務器把少量數據儲存到客戶端的硬盤或內存,從客戶端的硬盤讀取數據的一種技術;
下載與引入:jquery.cookie.js基于jquery;先引入jquery,再引入:jquery.cookie.js;下載:http://plugins.jquery.com/cookie/
<script type="text/javascript" src="js/jquery.min.js">
</script><script type="text/javascript" src="js/jquery.cookie.js"></script>
jquery.cookie.js代碼的內容并不多,可以直接拷貝一下
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(value)),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
1.添加一個"會話cookie"
$.cookie('the_cookie', 'the_value');
這里沒有指明 cookie有效時間,所創(chuàng)建的cookie有效期默認到用戶關閉瀏覽器為止,所以被稱為 “會話cookie(session cookie)”。
2.創(chuàng)建一個cookie并設置有效時間為 7天
$.cookie('the_cookie', 'the_value', { expires: 7 });
這里指明了cookie有效時間,所創(chuàng)建的cookie被稱為“持久 cookie (persistent cookie)”。注意單位是:天;
PS:這里好像是有問題啊,試了半天,發(fā)現jquery設置的cookie過期時間關閉瀏覽器就失效,https://www.cnblogs.com/acm-bingzi/p/jquery_cookie_expire.html
3.創(chuàng)建一個cookie并設置 cookie的有效路徑
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
在默認情況下,只有設置 cookie的網頁才能讀取該 cookie。如果想讓一個頁面讀取另一個頁面設置的cookie,必須設置cookie的路徑。cookie的路徑用于設置能夠讀取 cookie的頂級目錄。將這個路徑設置為網站的根目錄,可以讓所有網頁都能互相讀取 cookie (一般不要這樣設置,防止出現沖突)。
4.讀取cookie
$.cookie('the_cookie');
5.刪除cookie
$.cookie('the_cookie', null); //通過傳遞null作為cookie的值即可
6.可選參數
$.cookie('the_cookie','the_value',{
expires:7,
path:'/',
domain:'jquery.com',
secure:true
})
- expires:(Number|Date)有效期;設置一個整數時,單位是天;也可以設置一個日期對象作為Cookie的過期日期;
- path:(String)創(chuàng)建該Cookie的頁面路徑;
- domain:(String)創(chuàng)建該Cookie的頁面域名;
- secure:(Booblean)如果設為true,那么此Cookie的傳輸會要求一個安全協議,例如:HTTPS;
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
jquery判斷復選框選中狀態(tài)以及區(qū)分attr和prop
這篇文章主要介紹了jquery判斷復選框選中狀態(tài)以及區(qū)分attr和prop,感興趣的小伙伴們可以參考一下2015-12-12

