1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script src="js/jquery-1.12.3.js"></script> 7 <script src="js/jquery.cookie.js"></script> 8 <script> 9 $(function(){ 10 11 //cookie 12 //JS-cookie 13 //document.cookie = "name=value; expires=过期日期;path=访问路径;domain=域名;secure"; 14 //JQ-cookie 15 //$.cookie("name","zhangsan", {expires:7,path:"/"}); 16 17 //添加cookie 18 $.cookie("name","zhangsan", {expires:7,path:"/"}); 19 20 //修改cookie 21 //自动URI编码/解码 22 $.cookie("name", "张三", {expires:7, path:"/"}); 23 24 //获取cookie 25 console.log( $.cookie("name") ); //张三 26 27 //删除cookie 28 //将expires设置为0或负数 29 $.cookie("name", "", {expires:-1, path:"/"}); 30 console.log( $.cookie("name") ); //undefined 31 32 33 //存储对象 34 var obj = { 35 name: "张三", 36 age: 33 37 } 38 $.cookie("person", obj, {expires:30, path:"/"}); 39 console.log( $.cookie("person") ); //"[object Object]" 40 console.log( typeof $.cookie("person") ); //string 41 42 //JSON序列化: JSON.stringify() 将对象转换为字符串 43 //JSON解析:JSON.parse() 从字符串中解析出json对象 44 $.cookie("person", JSON.stringify(obj), {expires:30, path:"/"}); 45 console.log( $.cookie("person") ); //"{"name":"张三","age":33}" 46 console.log( JSON.parse($.cookie("person")).name ); //张三 47 48 49 //存储数组 50 var arr = []; 51 arr.push({name: "张三", age:33}); 52 arr.push({name: "李四", age:44}); 53 arr.push({name: "王五", age:55}); 54 55 //将arr进行序列化后再存储 56 $.cookie("persons", JSON.stringify(arr), {expires:30, path:"/"}); 57 console.log( $.cookie("persons") ); 58 //"[{"name":"张三","age":33},{"name":"李四","age":44},{"name":"王五","age":55}]" 59 60 61 }) 62 </script> 63 </head> 64 <body> 65 </body> 66 </html>
时间: 2024-11-01 13:53:54