简体   繁体   English

无法从 thymeleaf 中的 javascript 中解析 JSON object

[英]Can`t parse JSON object from in javascript from thymeleaf

In controller I put simple java object, mapped to JSON using jackson. In controller I put simple java object, mapped to JSON using jackson.

    Station station = stationRepo.findFirstByCodeEquals(320007);

    ObjectMapper objectMapper = new ObjectMapper();
    String JSONstation = objectMapper.writeValueAsString(station);
    model.addAttribute("station",JSONstation);

In front end I use Thymeleaf to get this object in tag:在前端,我使用 Thymeleaf 在标签中获取此 object:

<p id="test" th:text="${station}">Test 1</p>
<p id="test2">Test 2</p>
<p id="test3">Test 3</p>

And I simply get this JSON object in javascript using document.getElementById("test").innerText, and parse it into js object. And I simply get this JSON object in javascript using document.getElementById("test").innerText, and parse it into js object.

    var JSONtest = "[[${station}]]";
    var JSONstation = document.getElementById("test").innerText;

    document.getElementById("test2").innerHTML = typeof JSONtest;

    var jsStation = JSON.parse(JSONstation);


    document.getElementById("test3").innerHTML = JSONtest.rusName;

But when I thy to get JSON object from thymeleaf using var JSONtest = "[[${station}]]" I can`t parse it into js object, but they are the same. But when I thy to get JSON object from thymeleaf using var JSONtest = "[[${station}]]" I can`t parse it into js object, but they are the same. What am I do wrong in this code?我在这段代码中做错了什么?

When you are using Thymeleaf variables in JavaScript, you shouldn't pass them as a String . 在JavaScript中使用Thymeleaf变量时,不应将它们作为String传递。 Instead you should add the variable to the model as you normally would: 相反,您应该像往常一样将变量添加到模型中:

model.addAttribute("station", station);

and let Thymeleaf automatically translate it to JavaScript (it will handle the translation of your object to JSON, no need for you to use Jackson): 并让Thymeleaf自动将其翻译为JavaScript(它将处理您的对象到JSON的翻译,无需您使用Jackson):

<script th:inline="javascript">
    var JSONtest = /*[[${station}]]*/ {};
</script>

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

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