0

I'm trying to pass a string argument to JavaScript function. for some reason, it can get only ints. I put here only the syntax of the string, since I know that this is the problem because it worls with int.

Code inside sending function:

String counter = "hey";
out.println("<script>parent.update(\'' + counter + '\')</script>");
out.flush();

Eventually I'd expect following update function on my HTML page to be called with value of counter as shown above:

 <script>
      function update(p) { alert(p); }
 </script>

as I mentioned, the javascript file does alert when I send an int, but doesn't react when I send a string.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Zohar Argov
  • 143
  • 1
  • 1
  • 11

1 Answers1

0

What you are trying to do called "string interpolation" and used in other languages - you can have formatting string and get values automatically inserted to it.

The code you've used does not do that - since you pass just single string to out.println it is printed as is.

Your options

  • construct string with concatenation

    out.println("<script>parent.update('" +
       counter + 
       "')</script>");
    
  • use String.format as shown in String variable interpolation Java

    out.println(String.Format("<script>parent.update('%s')</script>",
       counter));
    

Note: if value you are trying to pass to JavaScript function may contain quotes (especially if coming from user's input) you'd need to escape it first.

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179