登录时,通过Ajax 获取token用于用户验证
//获取token
$.ajax({
url: '/user/login',
data: {
"Account": "ssy",
"Password": "123456"
},
type: "post",
dataType: "json",
success: function(data) {
var token = data.token;
//存放userTokenb
window.localStorage.setItem('userToken', token);
console.log(window.localStorage.getItem("userToken"))
}
})
var userToken = window.localStorage.getItem("userToken");
$.ajax({
//将token放入headers
headers: {
"token": userToken //此处放置请求到的用户token
},
url: "/user/List", //请求url
type: "post",
dataType: 'json',
data: {
},
success: (data) => {
console.log(data)
}
})
浏览器缓存sessinonStorage和localStorage
//sessinonStorage只在当前窗口有效 生命随浏览器关闭终止 容量约5M
window.sessionStorage.setItem("name",'男');
//获取name
console.log(window.sessionStorage.getItem('name'));
//清空Storage
window.sessionStorage.clear();
//删除数据
window.sessionStorage.removeItem('age')
a页代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a id="a1" href="./b.html" target="view_window"></a>
</body>
<script>
//sessinonStorage只在当前窗口有效 生命随浏览器关闭终止 容量约5M
window.sessionStorage.setItem("name", '法外狂徒张三');
//获取name
var name = window.sessionStorage.getItem('name')
console.log();
const a1 = document.getElementById('a1');
const text = document.createTextNode(name)
a1.appendChild(text)
</script>
</html>
b页代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a id="a1"></a>
</body>
<script>
//获取name
var name = window.sessionStorage.getItem('name')
const a1 = document.getElementById('a1');
const text = document.createTextNode(name)
a1.appendChild(text)
</script>
</html>
先打开a页面储存name 在打开桌面b获取时会获取不到如下图
image.png
image.png
但是在a页点击a链接跳转b却可以获取到
image.png
当跳转到b时修改name,在返回a页查看name, a页并没有发生改变(这说明a和b页面不是公用的一个sessionStorage,而是在页面跳转时a传给了b)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a id="a1"></a>
</body>
<script>
window.sessionStorage.setItem("name", '执法官李四');
var name = window.sessionStorage.getItem('name')
const a1 = document.getElementById('a1');
const text = document.createTextNode(name)
a1.appendChild(text)
</script>
</html>
image.png
//localStorage在关闭浏览器后依然有效 容量约20M
//放入缓存中
window.localStorage.setItem('userToken', token);
//获取
console.log(window.localStorage.getItem("userToken"))
//删除数据
window.sessionStorage.removeItem('userToken')
网友评论