高版本浏览器支持的缓存:
localStorage(本地的永久缓存)和sessionStroage(会话一关闭缓存就没了)
cookie(信息存储在cookie中,服务端可自动获取)
同一个网站中所有页面共享一个cookie(4KB)
过期时间 时间一到内容消失
存储容量没有localStorage和sessionStroage大
js的=表示覆盖,cookie的=表示添加
要想覆盖,name值需一致
添加用户名:
document.cookie = 'username = zhangsan';
cookie取值:
console.log(document.cookie);
cookie过期时间:
let oDate = new Date();oDate.setDate(oDate.getDate()+2);//重新设置日期对象,延迟两天document.cookie = 'username = zhangsan;expires=' + oDate;
删除cookie 设置过期时间,可以把对应name值删除
let oDate = new Date();
oDate.setDate(oDate.getDate()-1);
document.cookie = 'usename = zhangsan;expires=' + oDate;
封装cookie增删改:
<button onclick="setCookie('car','CT5',1)">设置car</button>
<button onclick="getCookie('car')">获取car</button><button onclick="delCookie('car')">删除car</button>
<script> function delCookie(name){ let oDate = new Date(); oDate.setDate(oDate.getDate()-1); document.cookie = name + '=;expires=' + oDate; } function getCookie(name){ let str = document.cookie; let arr1 =str.split(';'); //console.log(arr1); for(var i =0;i<arr1.length;i++){ //console.log(arr1[i]); var arr2 = arr1[i].split('='); //console.log(arr2); if(name==arr2[0].trim()){ console.log(arr2[1]); } } } //封装一个设置cookie的函数 function setCookie(name,value,time){ let oDate = new Date(); oDate.setDate(oDate.getDate() + time); document.cookie = name + '=' + value + ';expires=' + oDate; } </script>
ajax:
ajax 是一种无需重新加载整个网页的情况下,能够更新部分网页的技术局部更新
第一步:创建ajax对象
let xhr = new XMLHttpRequest();//new一个XMLHttpRequest的实例化对象
第二步:连接到服务器
open(方法,文件名,同步异步)三个参数:
一.post/get
二.请求的文件名
三.同步(false) 异步(true)
xhr.open('get','abc.txt','true');
第三步:发送请求
xhr.send();
第四步:接收返回值
xhr.onreadystatechange = function(){ /* 监听返回值 */ console.log(xhr.responseText); }