thymeleaf及JavaScript如何取controller中返回的model里的值,结合弹窗,亲测可用。
最新更新:不用alert弹窗了,改用jQuery的$.confirm
1、thymeleaf取controller返回的model中的值,2、JavaScript取取controller返回的model中的值, 3、以及thymeleaf整合JavaScript取controller返回的model中的值。
(仅适合低端玩家,譬如我这种)
在搞毕业设计的过程中,我一个做后端的,被逼无奈整前端,过程中遇到了一点坑,顺手发个文章也能帮助他人。
thymeleaf取值
@RequestMapping("/test1")
@Controller
public String test1( Model model){
model.addAttribute("test","TEST**TEST**TEST");
return "hello";
}
<h1>hello word!You success!</h1>
<h1 th:text="${test}">hello word!You success!</h1>
JavaScript取值
主要是将值传给hidden隐藏域
@RequestMapping("/test2")
@Controller
public String test2( Model model){
model.addAttribute("msg","TEST**TEST**TEST");
return "hello";
}
<input type="hidden" id="msg" th:value="${msg}" >
<script type="text/javascript" th:inline="javascript">
onload=function(){
var msg = $("#msg").val();
if(msg){
$.confirm({
title: '消息提示',
content: msg,
buttons: {
confirm: {
text: '确认',
action: function(){
// $.alert('确认的!');
// 这里是确认按钮点击后的操作
}
}
}
});
}
};
</script>
thymeleaf整合JavaScript取值
thymeleaf在3版本中加入了JavaScript的内联,使得用户可以使用JavaScript通过thymeleaf直接取返回值。
@RequestMapping("/test3")
public String test3( Model model){
model.addAttribute("msg","这是thymeleaf官方给出的方法,需要thymeleaf3才可以使用");
return "hello";
}
<script type="text/javascript" th:inline="javascript">
// th:inline="javascript" 必须写
onload=function(){
var msg = [[${msg}]]; //官方写法
if(msg){
$.confirm({
title: '消息提示',
content: msg,
buttons: {
confirm: {
text: '确认',
action: function(){
// $.alert('确认的!');
// 这里是确认按钮点击后的操作
}
}
}
});
}
};
</script>