Access velocity variable with javascript

2019-04-28 11:43发布

<head> #set($test = "works")) </head>

<script> 
    var get = "${test}"; // I also tried using '$test' and "$test" also

    alert(get);
</script> 

And it alerts out ${test}, but should print works.

How can I get it to work?

5条回答
forever°为你锁心
2楼-- · 2019-04-28 12:32

I realize the question is old, but this worked for me:

#set ($test = "hi")
<script>
    alert("$test");
</script>

Need to include quotes around the variable in the alert since it is a string.

查看更多
放荡不羁爱自由
3楼-- · 2019-04-28 12:33

try this...

    #set ($test = "works")

  <script type="text/javascript">
       var myvar = "${test}";
       alert (myvar);
  </script>

THIS WORKS SURELY!!!!

查看更多
Ridiculous、
4楼-- · 2019-04-28 12:33

Try var get = "$test"; instead of var get = "${test}";

查看更多
对你真心纯属浪费
5楼-- · 2019-04-28 12:42

Just use it as in html:

<script> 
    var get = $test;

    alert(get);
</script> 
查看更多
够拽才男人
6楼-- · 2019-04-28 12:45

I had that problem while using tiles, the only way i got it to work was to use the jstl c:out tag, like:

var get = "<c:out value='${test}' />";

that should work, and remember to add the jstl include on the top of the page

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
查看更多
登录 后发表回答