先看需求:
需要用户登录成功之后的购物车数据来初始化主页面购物车的商品数量,而在没有登录时,主页面的购物车不显示数量
没有登录
成功登录
那么这里需要在前端读到session/request/model任意一个中的值,就可以在js中做页面初始化
前端时间用的都是jsp做前端,可以直接获得session和request的值,但是现在的前端是html中引入了thymeleaf模板,而在htnl的
<script>
……
</script>
中又没法直接获得request/session的值,于是一度陷入困境,好在看到这篇帖子
Html中获取session中的值(实现登录后显示欢迎xxx)
其中有些细节说的不是很清楚,于是在此整理自己的思路
1.首先,没法在前端直接获取session/request/model中的值,但是,springboot支持的前端模板thymeleaf的标签语法支持直接从model中取值(或许也支持直接从request或session中直接取值,各位可以试试),例如
后端控制层写入了如下数据
那么在前端的html中,就可以使用如下方式,得到存在model中的字符串
注意,这里没有使用的是span标签的,th:text属性来获取后端数据,这点至关重要,后面会详说
这是我们spingboot项目,前端页面获取值,最常规方法,
那么,现在就可以开始在js中获取这个值了
首先认识一些使用到的方法
document.getElementById("aa")
定位到当前页面,id值为 “aa” 的标签
innerHTML
innerHTML在JS是双向功能:获取对象的内容 或 向对象插入内容
我们可以通过 document.getElementById(‘aa’).innerHTML 来获取id为aa的对象的内嵌内容;
也可以对某对象插入内容,如 document.getElementById(‘abc’).innerHTML=’这是被插入的内容’;
这样就能向id为abc的对象插入内容。
那么,通过
document.getElementById("user").innerHTML
就可以获得html中的span标签中的值,但是innerHTML只能获取,两个标签中的值,例如
<span id=“user”>这是数据</span>
而document.getElementById("user").innerHTML就能获取到
这就是数据
这段文字
只要这里能获取到,那么我们就能在js中利用这个数据做别的处理,至此我们实现了需求,在html中获取后端model中的数据
那么还有些额外内容,
如果把获取到的值利用sessionStorage.setItem存入对应的键名,就能在别的页面也使用这个数据,
sessionStorage.setItem('USER_NAME',document.getElementById("user").innerHTML);
在别的页面使用
sessionStorage.getItem('USER_NAME')
来获取这个值
页面初始化方法
window.onload = myfun; function myfun(){
……
}
在body中写入
<body οnlοad="load();">
这样在页面加载时,就会自动执行myfun()方法中的内容
利用js改变页面标签状态
document.getElementById('xtb1').setAttribute('href','#');
其中xtb1是对应标签的id,href是这个标签的属性,#是属性对应的值,
这样就可以在js中改变标签状态
后端代码
@PostMapping("/denglu")
public String denglu(String User_Pass, String User_Phone, Model model) {
User u = new User();
u.setUser_Phone(User_Phone);
u.setUser_Pass(User_Pass);
//调用登录方法
User one = this.user1.selectdenglu(u);
if (one != null) {
model.addAttribute("User_Name", "----------登录成功数据-----------");
return "index";
} else {
return "login";
}
}
前端代码
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<script type="application/javascript"> 、
window.onload = myfun;
function myfun(){
sessionStorage.setItem('USER_NAME',document.getElementById("user").innerHTML);
var user=sessionStorage.getItem('USER_NAME');
// 提示登录
if(user==""){
alert("需要登录!");
document.getElementById('xtb3').setAttribute('href','#');
}else
{
alert("登录成功!");
}
}
</script>
</head>
<body οnlοad="load();">
<header>
<span style="display: none" id="user" th:text="${User_Name}"></span>
</header>
</body>
</html>