jquery.cookie.js的介紹與使用方法
Cookie是由服務器端生成,發(fā)送給User-Agent(一般是瀏覽器),瀏覽器會將Cookie的key/value保存到某個目錄下的文本文件內(nèi),下次請求同一網(wǎng)站時就發(fā)送該Cookie給服務器(前提是瀏覽器設置為啟用cookie)。
例如購物網(wǎng)站存儲用戶曾經(jīng)瀏覽過的產(chǎn)品列表,或者門戶網(wǎng)站記住用戶喜歡選擇瀏覽哪類新聞。 在用戶允許的情況下,還可以存儲用戶的登錄信息,使得用戶在訪問網(wǎng)站時不必每次都鍵入這些信息?
怎么在js/jquery中操作處理cookie那?今天分享一個cookie操作類--jQuery.Cookie.js,是一個輕量級的Cookie管理插件。
一、什么是 cookie?
cookie 就是頁面用來保存信息,比如自動登錄、記住用戶名等等。
cookie 的特點
- 同個網(wǎng)站中所有的頁面共享一套 cookie
- cookie 有數(shù)量、大小限制
- cookie 有過期時間jquery.cookie.js 是一款輕量級的 cookie 插件,可以讀取,寫入和刪除 cookie。本文主要針對
jquery.cookie.js 的用法進行詳細的介紹。
二、jquery.cookie.js 使用方法
Cookies
定義:讓網(wǎng)站服務器把少量數(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.添加一個"會話cookie"
$.cookie('the_cookie', 'the_value');這里沒有指明 cookie有效時間,所創(chuàng)建的cookie有效期默認到用戶關(guān)閉瀏覽器為止,所以被稱為 “會話cookie(session cookie)”。
2.創(chuàng)建一個cookie并設置有效時間為 7天
$.cookie('the_cookie', 'the_value', { expires: 7 });這里指明了cookie有效時間,所創(chuàng)建的cookie被稱為“持久 cookie (persistent cookie)”。注意單位是:天;
3.創(chuàng)建一個cookie并設置 cookie的有效路徑
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });在默認情況下,只有設置 cookie的網(wǎng)頁才能讀取該 cookie。如果想讓一個頁面讀取另一個頁面設置的cookie,必須設置cookie的路徑。cookie的路徑用于設置能夠讀取 cookie的頂級目錄。將這個路徑設置為網(wǎng)站的根目錄,可以讓所有網(wǎng)頁都能互相讀取 cookie (一般不要這樣設置,防止出現(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ù)時,單位是天;也可以設置一個日期對象作為Cookie的過期日期;這個地方也要注意,如果不設置這個東西,瀏覽器關(guān)閉之后此cookie就失效了
path:(String)創(chuàng)建該Cookie的頁面路徑;cookie值保存的路徑,默認與創(chuàng)建頁路徑一致。
domain:(String)創(chuàng)建該Cookie的頁面域名;默認與創(chuàng)建頁域名一樣。 這個地方要相當注意,跨域的概念,如果要主域名二級域名有效則要設置 ".xxx.com"
secure:一個布爾值,表示傳輸cookie值時,是否需要一個安全協(xié)議。(Booblean)如果設為true,那么此Cookie的傳輸會要求一個安全協(xié)議,例如:HTTPS;
raw: true:默認值:false。 默認情況下,讀取和寫入cookie的時候自動進行編碼和解碼(使用encodeURIComponent編碼,decodeURIComponent解碼)。
要關(guān)閉這個功能設置raw: true即可。
三、完整實例
一個完整設置與讀取cookie的頁面代碼:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery學習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='張學友']").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="張學友" />張學友
</p>
<p><input type="button" value="保存" /></p>
</body>
</html>cookie本質(zhì)上是一個txt文本,因此只能夠存入字符串,對象通常要序列化之后才能存入cookie,而取的時候要反序列才又能得到對象。
$(function () {
if ($.cookie("o") == null) {
var o = { name: "張三", age: 24 };
var str = JSON.stringify(o); //對序列化成字符串然后存入cookie
$.cookie("o", str, {
expires:7 //設置時間,如果此處留空,則瀏覽器關(guān)閉此cookie就失效。
});
alert("cookie為空");
}
else {
var str1 = $.cookie("o");
var o1 = JSON.parse(str1); //字符反序列化成對象
alert(o1.name); //輸反序列化出來的對象的姓名值
}
})一個輕量級的cookie插件,可以讀取、寫入、刪除cookie。
四、小結(jié)和引深
1.jQuery操作cookie的插件,大概的使用方法如下:
$.cookie('the_cookie'); //讀取Cookie值
$.cookie('the_cookie', ‘the_value'); //設置cookie的值
$.cookie('the_cookie', ‘the_value', {expires: 7, path: ‘/', domain: ‘jquery.com', secure: true});//新建一個cookie 包括有效期 路徑域名等
$.cookie('the_cookie', ‘the_value'); //新建cookie
$.cookie('the_cookie', null); //刪除一個cookie2.jquery設置cookie過期時間與檢查cookies是否可用:
//讓cookies在x分鐘后過期
var date = new date();
date.settime(date.gettime() + (x * 60 * 1000));
$.cookie(‘example', ‘foo', { expires: date });
$.cookie(‘example', ‘foo', { expires: 7});//檢查當前瀏覽器不支持或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 是一個用于設置、讀取和刪除瀏覽器cookie的jQuery插件。以下是一些常用的方法和示例:
設置cookie:
$.cookie('name', 'value'); // 設置一個名為 'name' 值為 'value' 的cookie
$.cookie('name', 'value', { expires: 7 }); // 設置一個有7天過期時間的cookie讀取cookie:
var name = $.cookie('name'); // 獲取名為 'name' 的cookie值刪除cookie:
$.cookie('name', null); // 刪除名為 'name' 的cookie讀取所有cookie:
var allCookies = $.cookie(); // 返回一個包含所有cookie的對象
設置cookie屬性:
$.cookie('name', 'value', {
? ? expires: 7, // 設置cookie有效期為7天
? ? path: '/', // 設置cookie在整個站點有效
? ? domain: 'jquery.com', // 設置cookie對jquery.com域及其子域有效
? ? secure: true // 設置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)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
jquery.serialize() 函數(shù)語法及簡單實例
下面小編就為大家?guī)硪黄猨query.serialize() 函數(shù)語法及簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07
JQuery+Bootstrap 自定義全屏Loading插件的示例demo
這篇文章主要介紹了JQuery+Bootstrap 自定義全屏Loading插件,本文通過示例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07
淺析jQuery Ajax請求參數(shù)和返回數(shù)據(jù)的處理
這篇文章主要介紹了淺析jQuery Ajax請求參數(shù)和返回數(shù)據(jù)的處理的相關(guān)資料,需要的朋友可以參考下2016-02-02
創(chuàng)建公共調(diào)用 jQuery Ajax 帶返回值
請求Ajax 帶返回值,并彈出提示框提醒的實現(xiàn)代碼,需要的朋友可以參考下2012-08-08

