jquery.cookie.js的介紹與使用方法
Cookie是由服務(wù)器端生成,發(fā)送給User-Agent(一般是瀏覽器),瀏覽器會將Cookie的key/value保存到某個(gè)目錄下的文本文件內(nèi),下次請求同一網(wǎng)站時(shí)就發(fā)送該Cookie給服務(wù)器(前提是瀏覽器設(shè)置為啟用cookie)。
例如購物網(wǎng)站存儲用戶曾經(jīng)瀏覽過的產(chǎn)品列表,或者門戶網(wǎng)站記住用戶喜歡選擇瀏覽哪類新聞。 在用戶允許的情況下,還可以存儲用戶的登錄信息,使得用戶在訪問網(wǎng)站時(shí)不必每次都鍵入這些信息?
怎么在js/jquery中操作處理cookie那?今天分享一個(gè)cookie操作類--jQuery.Cookie.js,是一個(gè)輕量級的Cookie管理插件。
一、什么是 cookie?
cookie 就是頁面用來保存信息,比如自動登錄、記住用戶名等等。
cookie 的特點(diǎn)
- 同個(gè)網(wǎng)站中所有的頁面共享一套 cookie
- cookie 有數(shù)量、大小限制
- cookie 有過期時(shí)間jquery.cookie.js 是一款輕量級的 cookie 插件,可以讀取,寫入和刪除 cookie。本文主要針對
jquery.cookie.js 的用法進(jìn)行詳細(xì)的介紹。
二、jquery.cookie.js 使用方法
Cookies
定義:讓網(wǎng)站服務(wù)器把少量數(shù)據(jù)儲存到客戶端的硬盤或內(nèi)存,從客戶端的硬盤讀取數(shù)據(jù)的一種技術(shù);
下載與引入: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>
使用:
1.添加一個(gè)"會話cookie"
$.cookie('the_cookie', 'the_value');這里沒有指明 cookie有效時(shí)間,所創(chuàng)建的cookie有效期默認(rèn)到用戶關(guān)閉瀏覽器為止,所以被稱為 “會話cookie(session cookie)”。
2.創(chuàng)建一個(gè)cookie并設(shè)置有效時(shí)間為 7天
$.cookie('the_cookie', 'the_value', { expires: 7 });這里指明了cookie有效時(shí)間,所創(chuàng)建的cookie被稱為“持久 cookie (persistent cookie)”。注意單位是:天;
3.創(chuàng)建一個(gè)cookie并設(shè)置 cookie的有效路徑
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });在默認(rèn)情況下,只有設(shè)置 cookie的網(wǎng)頁才能讀取該 cookie。如果想讓一個(gè)頁面讀取另一個(gè)頁面設(shè)置的cookie,必須設(shè)置cookie的路徑。cookie的路徑用于設(shè)置能夠讀取 cookie的頂級目錄。將這個(gè)路徑設(shè)置為網(wǎng)站的根目錄,可以讓所有網(wǎng)頁都能互相讀取 cookie (一般不要這樣設(shè)置,防止出現(xiàn)沖突)。
4.讀取cookie
$.cookie('the_cookie');5.刪除cookie
$.cookie('the_cookie', null); //通過傳遞null作為cookie的值即可6.可選參數(shù)
$.cookie('the_cookie','the_value',{
expires:7,
path:'/',
domain:'jquery.com',
secure:true
}) expires:(Number|Date)有效期;設(shè)置一個(gè)整數(shù)時(shí),單位是天;也可以設(shè)置一個(gè)日期對象作為Cookie的過期日期;這個(gè)地方也要注意,如果不設(shè)置這個(gè)東西,瀏覽器關(guān)閉之后此cookie就失效了
path:(String)創(chuàng)建該Cookie的頁面路徑;cookie值保存的路徑,默認(rèn)與創(chuàng)建頁路徑一致。
domain:(String)創(chuàng)建該Cookie的頁面域名;默認(rèn)與創(chuàng)建頁域名一樣?! ∵@個(gè)地方要相當(dāng)注意,跨域的概念,如果要主域名二級域名有效則要設(shè)置 ".xxx.com"
secure:一個(gè)布爾值,表示傳輸cookie值時(shí),是否需要一個(gè)安全協(xié)議。(Booblean)如果設(shè)為true,那么此Cookie的傳輸會要求一個(gè)安全協(xié)議,例如:HTTPS;
raw: true:默認(rèn)值:false。 默認(rèn)情況下,讀取和寫入cookie的時(shí)候自動進(jìn)行編碼和解碼(使用encodeURIComponent編碼,decodeURIComponent解碼)。
要關(guān)閉這個(gè)功能設(shè)置raw: true即可。
三、完整實(shí)例
一個(gè)完整設(shè)置與讀取cookie的頁面代碼:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery學(xué)習(xí)2</title>
<script src="jQuery.1.8.3.js" type="text/javascript"></script>
<script src="jquery.cookie.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#username").val($.cookie("username"));
if ($.cookie("like") == "劉德華") {
$(":radio[value='劉德華']").attr("checked", 'checked')
}
else {
$(":radio[value='張學(xué)友']").attr("checked", 'checked')
}
$(":button").click(function () {
$.cookie("username", $("#username").val(), {
path: "/", expires: 7
})
$.cookie("like", $(":radio[checked]").val(), {
path: "/", expiress: 7
})
})
})
</script>
</head>
<body>
<p><input type="text" id="username" value="" /></p>
<p>
<input type="radio" name="like" value="劉德華" />劉德華
<input type="radio" name="like" value="張學(xué)友" />張學(xué)友
</p>
<p><input type="button" value="保存" /></p>
</body>
</html>cookie本質(zhì)上是一個(gè)txt文本,因此只能夠存入字符串,對象通常要序列化之后才能存入cookie,而取的時(shí)候要反序列才又能得到對象。
$(function () {
if ($.cookie("o") == null) {
var o = { name: "張三", age: 24 };
var str = JSON.stringify(o); //對序列化成字符串然后存入cookie
$.cookie("o", str, {
expires:7 //設(shè)置時(shí)間,如果此處留空,則瀏覽器關(guān)閉此cookie就失效。
});
alert("cookie為空");
}
else {
var str1 = $.cookie("o");
var o1 = JSON.parse(str1); //字符反序列化成對象
alert(o1.name); //輸反序列化出來的對象的姓名值
}
})一個(gè)輕量級的cookie插件,可以讀取、寫入、刪除cookie。
四、小結(jié)和引深
1.jQuery操作cookie的插件,大概的使用方法如下:
$.cookie('the_cookie'); //讀取Cookie值
$.cookie('the_cookie', ‘the_value'); //設(shè)置cookie的值
$.cookie('the_cookie', ‘the_value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true});//新建一個(gè)cookie 包括有效期 路徑域名等
$.cookie('the_cookie', ‘the_value'); //新建cookie
$.cookie('the_cookie', null); //刪除一個(gè)cookie2.jquery設(shè)置cookie過期時(shí)間與檢查cookies是否可用:
//讓cookies在x分鐘后過期
var date = new date();
date.settime(date.gettime() + (x * 60 * 1000));
$.cookie(‘example', ‘foo', { expires: date });
$.cookie(‘example', ‘foo', { expires: 7});//檢查當(dāng)前瀏覽器不支持或Cookie已被禁用呢?可以使用以下js代碼:
var dt = new Date();
dt.setSeconds(dt.getSeconds() + 60);
document.cookie = "cookietest=1; expires=" + dt.toGMTString();
var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
if(!cookiesEnabled) {
//沒有啟用cookie
alert("沒有啟用cookie ");
} else{
//已經(jīng)啟用cookie
alert("已經(jīng)啟用cookie ");
}五、最后附上源代碼
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};六、總結(jié)
jQuery.cookie.js 是一個(gè)用于設(shè)置、讀取和刪除瀏覽器cookie的jQuery插件。以下是一些常用的方法和示例:
設(shè)置cookie:
$.cookie('name', 'value'); // 設(shè)置一個(gè)名為 'name' 值為 'value' 的cookie
$.cookie('name', 'value', { expires: 7 }); // 設(shè)置一個(gè)有7天過期時(shí)間的cookie讀取cookie:
var name = $.cookie('name'); // 獲取名為 'name' 的cookie值刪除cookie:
$.cookie('name', null); // 刪除名為 'name' 的cookie讀取所有cookie:
var allCookies = $.cookie(); // 返回一個(gè)包含所有cookie的對象
設(shè)置cookie屬性:
$.cookie('name', 'value', {
? ? expires: 7, // 設(shè)置cookie有效期為7天
? ? path: '/', // 設(shè)置cookie在整個(gè)站點(diǎn)有效
? ? domain: 'jquery.com', // 設(shè)置cookie對jquery.com域及其子域有效
? ? secure: true // 設(shè)置cookie僅在HTTPS下傳輸
});確保在使用這些方法之前,你已經(jīng)在頁面中引入了jQuery庫和jQuery.cookie.js。例如:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
picLazyLoad 實(shí)現(xiàn)圖片延時(shí)加載(包含背景圖片)
下面小編就為大家?guī)硪黄猵icLazyLoad 實(shí)現(xiàn)圖片延時(shí)加載(包含背景圖片)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-07-07
jquery實(shí)現(xiàn)兩個(gè)圖片漸變切換效果的方法
這篇文章主要介紹了jquery實(shí)現(xiàn)兩個(gè)圖片漸變切換效果的方法,涉及jquery針對圖片的顯示與隱藏效果的實(shí)現(xiàn)技巧,需要的朋友可以參考下2015-06-06
jQuery Chart圖表制作組件Highcharts用法詳解
這篇文章主要介紹了jQuery Chart圖表制作組件Highcharts用法,詳細(xì)分析了Highcharts插件的功能與具體使用技巧及相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-06-06
jQuery 行背景顏色的交替顯示(隔行變色)實(shí)現(xiàn)代碼
主要是利用了jquery的attr為行添加樣式來實(shí)現(xiàn)的,具體的代碼如下。2009-12-12
jquery實(shí)現(xiàn)帶單選按鈕的表格行選中時(shí)高亮顯示
如果將選中的這條記錄的行高亮顯示,同時(shí)該行的單選按鈕也被選中了,這樣會提高用戶的體驗(yàn)的,于是本文下了個(gè)示例,有需要的朋友可以參考下2013-08-08
jquery網(wǎng)頁元素拖拽插件效果及實(shí)現(xiàn)
效果說明:配合已有css樣式,載入插件后,網(wǎng)頁元素可以隨意在窗口內(nèi)拖拽,設(shè)置了原位置半透明和拖拽半透明的效果選項(xiàng),可根據(jù)需要選擇。另外,當(dāng)頁面上有多個(gè)可拖拽元素時(shí),可以載入另外一個(gè)用于設(shè)置z-index的插件,模擬windows窗口點(diǎn)擊置頂效果。2013-08-08

