简体   繁体   English

如何在JavaScript中显示来自springboot控制器的值

[英]How to display the values coming from springboot controller in javascript

I have a controller which is passing the json object wrapped inside a model. 我有一个控制器,该控制器传递包装在模型中的json对象。

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

I would like to use these values in my javascript. 我想在我的JavaScript中使用这些值。 I am not able to do that. 我不能那样做。 However, I can see display these values in HTML. 但是,我可以看到以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>

I have also looked into this question How to get spring mvc controller model key value inside javascript? 我也已经研究了这个问题, 如何在javascript中获取spring mvc控制器模型键值? and tried both the options with or without quotes with no success. 并尝试使用带引号或不带引号的两个选项均未成功。

I have also tried defining in HTML: 我也尝试过用HTML定义:

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

and using getElementById in my javascript with no success: 并在我的JavaScript中使用getElementById失败:

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

Using thymeleaf inlining you can use the below: 使用百里香内联可以使用以下方法:

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

There are additional ways to access server side variables depending on your use case refer to http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining for more information. 根据您的用例,还有其他访问服务器端变量的方法,有关更多信息,请参见http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM