How to pass the value of one variable in the JSP to another in Javascript?

4

I'm trying to set the value of a variable inside a script tag with JSP expression language. I tried this way to check if the value was not empty:

<c:if test="${!empty newsletter.id}">
<script>
   $(function(){
      alert("Entrou no 'if'");
   })
</script>
</c:if>

And it worked, alert was normally displayed (so the newsletter.id attribute is not empty). I then tried to set the value of the variable like this:

<c:if test="${!empty newsletter.id}">
<script>
   $(function(){
      var foo = ${newsletter.content}; /* aqui... */
      alert(foo);
   });
</script>
</c:if>

And then the alert stopped appearing. I even thought it was something because of the ${...} syntax with that of jQuery $(...) and I tried this way:

<c:if test="${!empty newsletter.id}">
<script>
   var foo = ${newsletter.content}; /* tentei fora do document.ready(...) */
   $(function(){
      alert(foo);
   });
</script>
</c:if>

alert did not appear either.

The problem is that it is time to assign the value of newsletter.content to the foo variable in Javascript. How do I assign a value of a JSP variable to a variable within the script tag?

    
asked by anonymous 08.05.2015 / 18:18

1 answer

4
var foo = '${newsletter.content}';

When placing the apostrophes, everything in newsetter.content will be placed inside a String. Actually you are using Java to generate Javascript code, so if the content of newsletter.content was "hello world" for example, the way it was would generate the following js code:

var foo = olá mundo;

Now with the apostrophes the generated code is:

var foo = 'olá mundo';
    
08.05.2015 / 18:35