Javascript 在此上下文中,只允许返回数字或布尔值的变量表达式
我试图向javascript函数传递一个值,但该函数调用依赖于一个布尔变量。在我最近升级到thymeleaf security 5之前,我一直可以很好地工作 这是代码片段Javascript 在此上下文中,只允许返回数字或布尔值的变量表达式,javascript,html,spring,spring-boot,thymeleaf,Javascript,Html,Spring,Spring Boot,Thymeleaf,我试图向javascript函数传递一个值,但该函数调用依赖于一个布尔变量。在我最近升级到thymeleaf security 5之前,我一直可以很好地工作 这是代码片段 <body th:onload="${timerEnabled} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'"> 我如何解决这个问题?谢谢。我可以用这种方法让它工作 <body> <script th:inline="javas
<body th:onload="${timerEnabled} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'">
我如何解决这个问题?谢谢。我可以用这种方法让它工作
<body>
<script th:inline="javascript">
/*<![CDATA[*/
var flag = [[${timerEnabled}]]; // if timer should be included or not
var timeRemaining = [[${timeRemaining}]]; // the time remaining.
window.onload = function() {
if(!flag)
return; // Exit/Return if the variable is false
runTimer(timeRemaining); // Call your favourite method if the variable is true
};
/*]]>*/
</script>
/**/
任何其他方法,如例外情况中建议的方法,我们都将不胜感激。请尝试这种方法
<body th:onload="${timerEnabled eq true} ? 'javascript:runTimer(\'' + ${timeRemaining} + '\');'">
我知道,另一个版本看起来确实好得多,但既然它不起作用,这个也没那么糟糕。当然,在这种情况下,我不建议把它加入你的身体
我觉得奇怪的是,我尝试了你的代码,它在我这方面确实有效。谁知道为什么会出现这样的错误。自从Thymeleaf 3.0.10以来,他们修复了一个关于未替换代码的安全漏洞 试一试
或推荐的方式:
<body th:data1="${timerEnabled}"
th:data2="${timeRemaining}"
th:onload="this.getAttribute('data1') ? javascript:runTimer(this.getAttribute('data2'));">
欲了解更多信息:
以及:
为什么它被标记为
spring boot
?因为这是一个spring boot应用程序,我刚刚升级到了2.0.6。也许我不必给它贴标签。我认为这会有所帮助。我只是尝试了你的代码片段,但它不起作用。我意识到问题在于将“String”变量传递给处理程序中的javascript函数(onload)。我升级后开始出现这个错误,可能是因为updte。即使是使用th:if
?我两个都试过了,都成功了。必须是更新,但这很奇怪。if中的一个也给出了错误,但要求我将内容分为两个独立的块。我认为这是因为更新,他们使它成为一种严格的模式,不允许根据异常直接在句柄中传递字符串。再次感谢你,因为我从你的回答中学到了一些新的东西。你是指第一个例子还是第二个?到2019年,你说的任何特定版本的thymeleaf是什么意思?我可以确认这是有效的!2019年使用最新的thymeleaf。这比前面提到的th:inlinejavascript
方法要好得多,而且更简洁,在该方法中,您可以像前面提到的其他答案一样使用CDATA
。
<th:block th:if="${timerEnabled} eq true">
<body th:onload="javascript:runTimer(\'' + ${timeRemaining} + '\');'">
</body>
</th:block>
<th:block th:if="${timerEnabled} eq false">
<body></body>
</th:block>
<body th:onload="[[${timerEnabled}]] ? 'javascript:runTimer(\'' +
[[${timeRemaining}]] + '\');'">
<body th:data1="${timerEnabled}"
th:data2="${timeRemaining}"
th:onload="this.getAttribute('data1') ? javascript:runTimer(this.getAttribute('data2'));">