ajax的url中使用thymeleaf的变量
在使用Thymeleaf和AJAX时,我们可以使用Thymeleaf的内联表达式(inline expression)将变量注入到JavaScript代码中。
例如,我们可以将Thymeleaf变量注入到AJAX的URL中,如下所示:
<script th:inline="javascript">
$(document).ready(function() {
var userId = [[${userId}]];
$.ajax({
url: '/user/' + userId + '/profile',
type: 'GET',
success: function(data) {
// 处理返回的数据
}
});
});
</script>
在这个例子中,我们使用[[${userId}]]将Thymeleaf变量userId注入到了AJAX请求的URL中。这个URL会被渲染成/user/123/profile的形式,其中123是Thymeleaf变量userId的值。
需要注意的是,在使用Thymeleaf内联表达式时,我们需要将<script>标签的th:inline属性设置为javascript,以告诉Thymeleaf这是一段JavaScript代码。
原文地址: https://www.cveoy.top/t/topic/baBP 著作权归作者所有。请勿转载和采集!