如何利用js、jquery操作cookie实现记住密码功能——jquery篇【转】
对cookies的操作在当访问一个网站就无时无刻的都伴随着我们,记录着我们的一举一动,并将不危害用户隐私的信息,将以保存,这样用户就不用去从新再次操作重复的步骤,这样大大方便了客户,也增加了客户对网站的回头率。
jquery.cookie.js 提供了jquery中非常简单的操作cookie的方法。
$.cookie('the_cookie'); // 获得cookie
$.cookie('the_cookie', 'the_value'); // 设置cookie
$.cookie('the_cookie', 'the_value', { expires: 7 }); //设置带时间的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 包括有效期 路径 域名等
这个插件默认的过期是按天数计算的,我们可以修改下,按毫秒计算,修改如下:
1 if (typeof options.expires === 'number') { 2 var seconds = options.expires, 3 t = options.expires = new Date(); 4 t.setTime(t.getTime() + seconds); 5 }
下面举个简单的例子:我们需要对某个页面进行阅读统计,但是呢,在一段时间里(比如5分钟),同一个人无论刷新了这个页面多少次都好,都只能算一次。这个时候可以借助cookie来实现:
1 <script language="javascript" src="http://www.nowamagic.net/zt/access_count/js/jquery-1.4.2.min.js"></script> 2 <script type="text/javascript" src="http://www.nowamagic.net/zt/access_count/js/jquery.cookie.js"></script> 3 <script language="javascript" src="http://www.nowamagic.net/zt/access_count/js/jquery.jsonp-2.1.4.min.js"></script> 4 <script type="text/javascript"> 5 // 页面类型,标识一组页面 6 var pageType = 20110420; 7 // 页面id,标识唯一一个页面 8 var url = window.location.href; 9 var url_arr = url.split("."); 10 var id = url_arr[url_arr.length - 2]; 11 12 $(document).ready(function(){ 13 init_count(pageType, id); 14 }) 15 16 // 初始化数据,同一个cookie一分钟的访问量都算一次 17 function init_count(pageType, id){ 18 if($.cookie('the_cookie'+id)){ //cookie已存在 19 getViewData(pageType, id); 20 } 21 else 22 { 23 // 1分钟过期 24 var cookie = $.cookie('the_cookie'+id, 'Gonn', { expires: 1000 * 60 * 5 }); 25 insert_page(pageType, id); 26 } 27 } 28 29 // 不插入与更新时统计访问量 30 function getViewData(pageType, id){ 31 $.ajax({ 32 type: "get", //使用get方法访问后台 33 dataType: "jsonp", //返回json格式的数据 34 jsonp:"callback", 35 url: "http://www.nowamagic.net/zt/access_count/manage.php", //要访问的后台地址 36 data:{"opp":"view", "pageType":pageType, "id":id}, 37 async: false, 38 success: function(data){46 39 $('#pc_1').html(data.total); 40 $('#pcm_1').html(data.record); 41 } 42 }) 43 } 44 45 // 插入或者更新页面统计 46 function insert_page(pageType, id){ 47 var j = null; 48 $.ajax({ 49 type: "get", //使用get方法访问后台 50 dataType: "jsonp", //返回json格式的数据 51 jsonp:"callback", 52 url: "http://www.nowamagic.net/zt/access_count/manage.php", //要访问的后台地址 53 data:{"opp":"insert", "pageType":pageType, "id":id}, 54 async: false, 55 success: function(data){ 56 j = data; 57 $('#pc_1').html(data.total); 58 $('#pcm_1').html(data.record); 59 } 60 }) 61 } 62 63 </script>
代码就直接原汁原味地贴上来吧,做个记录。