【问题标题】:How to display the values coming from springboot controller in javascript如何在javascript中显示来自springboot控制器的值
【发布时间】:2019-01-16 17:33:50
【问题描述】:

我有一个控制器,它传递包裹在模型中的 json 对象。

@RequestMapping("/template")
public String showTemplate(Model model) {       
    JSONObject obj = new JSONObject();
    obj.put("equipmentID", "30584D277D6D4568B17EBB8917D0CB15");
    model.addAttribute("template",obj);
    return "templates";
}

我想在我的 javascript 中使用这些值。我无法做到这一点。但是,我可以看到在 HTML 中显示这些值。

<head>
<script>
    function test()
    {
    var temp = "${template}";
    alert(temp); // The values are not displayed here
    }
</script>

<body onload="test()">
    <span th:text="${template}"> </span> //I can display the values here        
<body>

我还研究了这个问题How to get spring mvc controller model key value inside javascript? 并尝试了带或不带引号的选项,但均未成功。

我也尝试过在 HTML 中定义:

        <input type="hidden" id="templates" value='${template}'/>       

在我的 javascript 中使用 getElementById 没有成功:

        var template = document.getElementById("templates");

【问题讨论】:

  • 我也在为同样的问题苦苦挣扎,兄弟……你解决了这个问题了吗?

标签: javascript java spring-boot model-view-controller


【解决方案1】:

使用 thymeleaf 内联,您可以使用以下内容:

<script th:inline="javascript">
var message = [[${template}]];
alert(template);
</script>

根据您的用例,还有其他访问服务器端变量的方法,请参阅http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining 了解更多信息。

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 2015-05-03
    • 1970-01-01
    • 2019-04-07
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多