http本身是无状态的,也就是你浏览一个网页关闭后第二次再浏览这个网页服务器不会发现是同一个人浏览的,为了弥补http无状态就出现了cookie。
- cookie
在我们第一次请求服务器的时候是无cookie的,服务器在收到请求以后会在http的响应里添加头部Set-Cookie,并且在Set-Cookie里进行标识在下一次请求的时候浏览器就会在http请求头部里添加Cookie,以后每一次的http请求都要把Cookie传递给服务器。
<html>
//html代码省略
</html>
<script>
const username = document.querySelector('input[type="username"]')
const checkbox = document.querySelector('input[type="checkbox"]')
const submit = document.querySelector('input[type="submit"]')
submit.addEventListener('click', e => {
if (checkbox.checked && username.value !== ''){
let key = 'username'
let value = encodeURIComponent(username.value)
twoDays = 2 * 24 * 60 * 60
document.cookie = `${key}=${value}
}
e.preventDefault()
})
let arry = document.cookie.split(';').map(item => item.split('='))
let cookie = {}
for (let i = 0
let name = arry[i][0]
let value = arry[i][1]
cookie[name] = decodeURIComponent(value)
}
if (document.cookie) {
username.value = cookie.username
checkbox.checked = true
}
</script>
- localStorage
localStorage会永远保存在浏览器中,可以自行删除。localStorage虽然保存下来但是不参与服务器通信web存储容量比cookie大很多,但是localStorage是同步机制会影响浏览器的渲染进度。
- 下面使用localStorage简单模仿一下“历史搜索记录”
<html>
</html>
<script>
const input = document.querySelector('input[type="text"])
const button = document.querySelector('button')
const history = document.querySelector('.history')
if (localStorage.length > 0) {
let key = localStorage.key[i]
let li = document.creatElement('li')
let liText = document.creatTextNode(localStorage.getItem(key))
li.appendChild(liText)
history.appendChild(li)
let close = document.creatElement('span')
li.appendChild(close)
close.addEventListener('click', e => {
localStorage.removeItem(key)
li.parentNode.removeChild(li)
})
}
button.addEventListener('click', e => {
let key = new Date().valueOf()
let value = input.value
localStorage.setItem(key, value)
input.value = ''
let li = document.creatElement('li')
let liText = document.creatTextNode(localStorage.getItem(key))
li.appendChild(liText)
history.appendChild(li)
let close = document.creatElement('span')
li.appendChild(close)
close.addEventListener('click', e => {
localStorage.removeItem(key)
li.parentNode.removeChild(li)
})
})
</script>
- sessionStorage
sessionStorage也会保存在浏览器中,只不过关闭窗口就会被删除。
sessionStorage使用方法和localStorage类似
| cookie |
|---|
| 大小 | 4kb |
| 兼容 | h4/h5 |
| 访问 | 任何窗口 |
| 有效期 | 可手动设置 |
| 存储位置 | 浏览器和服务器 |
| 与请求一起发送 | 是 |
| localStorage | sessionStorage |
|---|
| 10Mb | 5Mb |
| h5 | h5 |
| 任何窗口 | 同一窗口 |
| 无 | 窗口关闭 |
| 浏览器 | 浏览器 |
| 否 | 否 |