Can I communicate between JavaScript code and JSP?

I need to use JavaScript code to perform some user interaction based on data that is stored in a database. How can I get this data to the JavaScript code using JSP? And how can I communicate back from JavaScript code to JSP.
Answer:
The book contains a brief example of how you can generate JavaScript code from a JSP page. It does not show how to pass variables between the two environments, but it does describe in some detail the main concepts you need to understand: that JSP code executes on the server and JavaScript code executes in the browser.Given that, the only way to pass variable values from JSP code to JavaScript code is to generate JavaScript variable assignments dynamically in the JSP page, e.g.

<script language="JavaScript">
  // JavaScript code
  var choices = new Array();
  <%
    // Java code in a JSP scriptlet that assigns the
    // JavaScript array elements to values of a Java
    // array created earlier in the JSP page.
    for (int i = 0; i < aJavaArray.length; i++) {
  %>
      choices[<%= i %>] = "<%= aJavaArray[i] %>";
  <% } %>
  // More JavaScript code
  ...
</script>

In the other direction, the only way is to use JavaScript to set HTTP parameter values that get sent with a request for a JSP page, e.g. setting the value of a hidden field.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>