對cookies的操作在當(dāng)訪問一個網(wǎng)站就無時無刻的都伴隨著我們,記錄著我們的一舉一動,并將不危害用戶隱私的信息,將以保存,這樣用戶就不用去從新再次操作重復(fù)的步驟,這樣大大方便了客戶,也增加了客戶對網(wǎng)站的回頭率。
jquery.cookie.js 提供了jquery中非常簡單的操作cookie的方法。
- $.cookie('the_cookie'); // 獲得cookie
- $.cookie('the_cookie', 'the_value'); // 設(shè)置cookie
- $.cookie('the_cookie', 'the_value', { expires: 7 }); //設(shè)置帶時間的cookie
- $.cookie('the_cookie', '', { expires: -1 }); // 刪除
- $.cookie('the_cookie', null); // 刪除 cookie
- $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});//新建一個cookie 包括有效期 路徑 域名等
這個插件默認(rèn)的過期是按天數(shù)計(jì)算的,我們可以修改下,按毫秒計(jì)算,修改如下:
1 | if ( typeof options.expires === 'number' ) { |
4 | var seconds = options.expires, t = options.expires = new Date(); |
5 | t.setTime(t.getTime() + seconds); |
下面舉個簡單的例子:我們需要對某個頁面進(jìn)行閱讀統(tǒng)計(jì),但是呢,在一段時間里(比如5分鐘),同一個人無論刷新了這個頁面多少次都好,都只能算一次。這個時候可以借助cookie來實(shí)現(xiàn):
04 | <script type= "text/javascript" > |
06 | var pageType = 20110420; |
08 | var url = window.location.href; |
09 | var url_arr = url.split( "." ); |
10 | var id = url_arr[url_arr.length - 2]; |
14 | $(document).ready( function (){ |
15 | init_count(pageType, id); |
19 | function init_count(pageType, id){ |
20 | if ($.cookie( 'the_cookie' +id)){ |
22 | getViewData(pageType, id); |
27 | var cookie = $.cookie( 'the_cookie' +id, 'Gonn' , { expires: 1000 * 60 * 5 }); |
31 | insert_page(pageType, id); |
37 | function getViewData(pageType, id){ |
43 | data:{ "opp" : "view" , "pageType" :pageType, "id" :id}, |
45 | success: function (data){ |
47 | $( '#pc_1' ).html(data.total); |
48 | $( '#pcm_1' ).html(data.record); |
54 | function insert_page(pageType, id){ |
61 | data:{ "opp" : "insert" , "pageType" :pageType, "id" :id}, |
63 | success: function (data){ |
69 | $( '#pc_1' ).html(data.total); |
70 | $( '#pcm_1' ).html(data.record); |
代碼就直接原汁原味地貼上來吧,做個記錄。
原文:http://www.nowamagic.net/jquery/jquery_JqueryCookie.php