admin管理员组

文章数量:1401849

How can I pass the value of a variable from javascript to a java variable?

<% String st = "<script>document.writeln(selected)</script>";
 out.print("value = " + st);%>

This is my code for java getting the values from javascript variable, selected. But no value is displayed.

How can I pass the value of a variable from javascript to a java variable?

<% String st = "<script>document.writeln(selected)</script>";
 out.print("value = " + st);%>

This is my code for java getting the values from javascript variable, selected. But no value is displayed.

Share Improve this question edited Dec 26, 2012 at 9:48 Erwin Brandstetter 661k157 gold badges1.1k silver badges1.3k bronze badges asked Dec 26, 2012 at 8:38 T E MT E M 551 gold badge2 silver badges8 bronze badges 4
  • 1 Javascript executes on client side, Java executes on server side. You cannot pass values between these two directly. – Pradeep Simha Commented Dec 26, 2012 at 8:40
  • Hmm.. then how can i make them municate knowing that they are in different side of programming? :) – T E M Commented Dec 26, 2012 at 8:42
  • possible duplicate of javascript to jsp – Thilo Commented Dec 26, 2012 at 8:44
  • <% String st = "<script>document.writeln(selected)</script>"; out.print("value = " + st);%> this is my code for java getting the values from javascript variable, selected. but no value is displayed – T E M Commented Dec 26, 2012 at 8:49
Add a ment  | 

4 Answers 4

Reset to default 3

You have to make a request and send your variable from the browser (where Javascript lives) to the server (where the JSP lives) that way.

Ajax would work, or an HTML form.

In you JSP, you can then receive it as a request parameter (or as part of the request body, or as a request header).

Javascript runs on client. JSP runs on server. The only way to pass information from client to server in web environment is via HTTP parameters or HTTP headers during HTTP request or as a part of request body if method is POST or PUT.

So, you should create such request. It can be done using either changing of your document location or utilizing AJAX call.

you can pass parameter or make a hidden field inside your jsp code and using javascript assign value for this hidden field, then get parameter value in java code.

Use HTML forms.

On server side, you'll get the data in HTTPServletRequest parameter.

Check this too: Building my first Java Web Application

本文标签: javaJAVASCRIPT values to JSP variablesStack Overflow