1、本地存储
本地存储指的是在客户端(浏览器)中保存数据的一种技术,可以在后续访问中读取,而不必重新向服务器提交请求。
举例:
使用 HTML5 提供的 LocalStorage API 进行本地存储:
使用 HTML5 提供的 LocalStorage API 进行本地存储:
// 写入 'name': 'John'
localStorage.setItem('name', 'John');
// 读取
let name = localStorage.getItem('name');
console.log(name); // John
2、缓存
缓存的概念是以使用本地缓存来快速访问已经被访问过的文件,以加快网页的载入速度。以下是一个使用 cookie 来设置缓存的示例
```JavaScript
function setCookie(cname, cvalue, exdays) {
const d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000)); // exdays 为有效时间,单位是天
const expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
const name = cname + "=";
const ca = document.cookie.split(';');
for(let i=0; i<ca.length; i++){
let c = ca[i];
while (c.charAt(0) === ' '){
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// example
setCookie('username', 'alice', 5); // 设置 username 键值对, 值为 alice,有效期为 5 天
getCookie('username'); // 获取 username 键值对的值
```