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

Asked

Viewed 2,159 times

4

I’m trying to define the value of a variable within a tag script with JSP expression language. I tried this to check that the value was not empty:

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

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

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

And that’s it, the Alert stopped being displayed. I even thought it was something because of the syntax ${...} with the jQuery $(...) and tried so:

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

The Alert.

The problem is when assigning the value of newsletter.content for the variable foo in Javascript. How do I assign a value from a JSP variable to a variable within the tag script?

1 answer

4


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

By placing the apostrophes, whatever is on newsetter.content will be placed inside a String. In fact 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';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.