0

Hi I have a jsp page where I have some variable. I want to access the variable in a javascript array. How can I get this?

Demo.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
       <%
int i=1;
int j=2;
int k=3;
int l=4;
%> 

   </body>
</html>

I want to use these 4 variables in the javascript array and print them. How can I achieve this?

2

3 Answers 3

2

Try,

<script language="JavaScript">  
    var Arr = new Array(); 
    Arr[0] = '<%=i %>';
    Arr[1] = '<%=j %>';
    Arr[2] = '<%=k %>';
    Arr[3] = '<%=l %>';
</script>
Sign up to request clarification or add additional context in comments.

Comments

2

In Java script you have to use scriplet tag to use jsp data.

<%
  Integet a = i ; //here i is your jsp variable
%>

In order to make this work you should declare the variable before using it (as always):

<%
    String myVar="blabla";
%>
<script type="text/javascript">
    foo();
    function foo() {
        var value = "<%=myVar%>";
        alert(value);
    }
</script>

Or :

var result = [];
result.push(<%i%>);
result.push(<%j%>);
result.push(<%k%>);
result.push(<%l%>);

Comments

0

You can access it using JSTL.

  1. set java variable to JSTL variable

  2. Access it in Java script as

    var x='${jstl_varialbe_goes_here }'; alert(x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.