Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass JavaScript values to Scriptlet in JSP?

Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?

like image 399
user601367 Avatar asked Apr 18 '11 09:04

user601367


4 Answers

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>
like image 163
harishtps Avatar answered Oct 16 '22 08:10

harishtps


Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.

To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.

like image 29
Joeri Hendrickx Avatar answered Oct 16 '22 10:10

Joeri Hendrickx


simple, you can't!

JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.

like image 2
Stijn Geukens Avatar answered Oct 16 '22 10:10

Stijn Geukens


I've interpreted this question as:

"Can anyone tell me how to pass values for JavaScript for use in a JSP?"

If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.

<html>
    <body>
        <script type="text/javascript">
            var serverInfo = "<%=getServletContext().getServerInfo()%>";
            alert("Server information " + serverInfo);
        </script>
    </body>
</html>
like image 1
Jim Blackler Avatar answered Oct 16 '22 08:10

Jim Blackler