将js中定义的变量传递给thymeleaf
时间: 2024-02-06 19:09:41 浏览: 126
要将JavaScript中定义的变量传递给Thymeleaf,你可以使用AJAX来实现。具体步骤如下:
1. 在JavaScript中定义一个变量,并将其发送到后端,可以使用jQuery的`$.ajax()`方法:
```
var myVar = "Hello World";
$.ajax({
url: "/myController/myMapping",
type: "POST",
data: {myVar: myVar},
success: function(response) {
console.log(response);
}
});
```
2. 在后端的Controller中,通过`@RequestParam`注解接收该变量:
```
@Controller
public class MyController {
@PostMapping("/myMapping")
public String myMapping(@RequestParam("myVar") String myVar, Model model) {
model.addAttribute("myVar", myVar);
return "myTemplate";
}
}
```
3. 在Thymeleaf模板中,通过`${}`表达式来获取该变量:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>My Template</title>
</head>
<body>
<p th:text="${myVar}"></p>
</body>
</html>
```
这样,在页面中就能显示出JavaScript中定义的变量了。
阅读全文
相关推荐

















