thymeleaf 传递数据到js变量

如何把控制器传来的model中的值传递给js变量呢?

下面便会找到答案...


1.controller


2.not work


3.ok


  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要将JS中的变量传递Thymeleaf,需要使用AJAX或表单提交。以下是两种方法: 1. AJAX方式 使用AJAX可以异步地将数据发送到服务器,然后从服务器响应中获取结果。在JS中,可以使用XMLHttpRequest对象来实现AJAX请求。例如: ```javascript var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { // 获取服务器响应 var data = xhr.responseText; // 将数据传递Thymeleaf document.getElementById("data").innerHTML = data; } else { console.error(xhr.statusText); } } }; xhr.open("POST", "/your/url", true); xhr.setRequestHeader("Content-Type", "application/json"); xhr.send(JSON.stringify({ "variable": yourVariable })); ``` 在Thymeleaf模板中,可以使用Thymeleaf的表达式语言(EL)来获取传递的参数。例如: ```html <div th:text="${variable}" id="data"></div> ``` 2. 表单提交方式 使用表单提交可以将数据同步地发送到服务器,然后重新加载页面以显示结果。在JS中,可以通过创建一个表单元素并将其添加到DOM中来实现表单提交。例如: ```javascript var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "/your/url"); var input = document.createElement("input"); input.setAttribute("type", "hidden"); input.setAttribute("name", "variable"); input.setAttribute("value", yourVariable); form.appendChild(input); document.body.appendChild(form); form.submit(); ``` 在Thymeleaf模板中,可以使用Thymeleaf的表达式语言(EL)来获取表单提交的参数。例如: ```html <div th:text="${param.variable}" id="data"></div> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值