导航

JavaScript学习心得(八)

Posted on 2014-03-17 23:00  菜鸟展翅  阅读(365)  评论(0编辑  收藏  举报

  Cookie是Netscape发明的技术,是动态网站必不可少的部分,用于浏览器请求Web页面的超文本传输协议是一种无状态的协议。

  两种方法维护状态:使用会话(session)(使用服务器技术实现,数据存储在服务器上)和Cookie(用服务器技术或者浏览器中的JavaScript管理)。

  Cookie包含多个不相关的信息块:

  • 名称
  • 到期日期和时间:必须格式化为UTC字符串
  • 有效路径(默认为当前路径):在服务器上的有效路径
  • 域(默认当前主机)

  Cookie容易在用户计算机上看到,不该用于存储敏感信息,在过程中始终验证Cookie值。关注安全的应用程序建议始终使用由服务器技术实现的回话。

  创建Cookie: document.cookie = value; Cookie使用特定的语法——cookieName = cookieValue; document.cookie = 'fontSize = 14'; 

  读取Cookie时,是全部读取,单独读取每个Cookie,先拆解字符串然后for循环遍历:

1 var coolies = document.cookie.split(';');
2 for(var i = 0,count = cookies.length; i<count;i++){
3
4     }

 创建程序库:

 1 // This script defines an object that has some cookie functions.
 2 
 3 // Create one global object:
 4 var COOKIE = {
 5     
 6     // Function for setting a cookie:
 7     setCookie: function(name, value, expire) {
 8         'use strict';
 9 
10         // Add validation!
11 
12         // Begin creating the value string:
13         var str =  encodeURIComponent(name) + '=' + encodeURIComponent(value);
14     //encodeURIComponent() 函数可把字符串作为 URI 组件进行编码。避免可能有问题的字符,预防服务器问题
15         // Add the expiration:
16         str += ';expires=' + expire.toGMTString(); 
17     
18         // Create the cookie:
19         document.cookie = str;
20 
21     }, // End of setCookie() function.
22     
23     // Function for retrieving a cookie value:
24     getCookie: function(name) {
25         'use strict';
26 
27         // Useful to know how long the cookie name is:
28         var len = name.length;
29         
30         // Split the cookie value:
31         var cookies = document.cookie.split(';');
32 
33         // Loop through the values:
34         for (var i = 0, count = cookies.length; i < count; i++) {
35 
36             // Lop off an initial space:
37             var value = (cookies[i].slice(0,1) == ' ') ? cookies[i].slice(1) : cookies[i];
38 
39             // Decode the value:
40             value = decodeURIComponent(value);
41 
42             // Check if this iteration matches the name:
43             if (value.slice(0,len) == name) {
44 
45                 // Return the part after the equals sign:
46                 return value.split('=')[1];
47 
48             } // End of IF.
49             
50         } // End of FOR loop.
51             
52         // Return false if nothing's been returned yet:
53         return false;
54 
55     }, // End of getCookie() function.
56     
57     // Function for deleting cookies:
58     deleteCookie: function(name) {
59         'use strict';
60         document.cookie = encodeURIComponent(name) + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT';
61     } // End of deleteCookie() function.
62 
63 }; // End of COOKIE declaration.
View Code

 定时器:

  • setTimeOut()
  • setInterval():指定时间间隔重复调用函数,必须有终止定时器的代码

  函数不能保证在精确的时间间隔调用,因为单线程。

  定时器主要用于动画、特效、页面自动更新内容。