Shubham
Shubham

Reputation: 107

Accessing a JSP (using JSTL) variable in INCLUDED javascript file which is included in the same JSP

Here is a snippet from my JSP file

  <c:set var="myVar">
        <spring:eval
            expression="@propertyConfigurer.getProperty('someproperty.in.file')" />
        </c:set>
  <script src="js/myJavascript.js"></script>

How do I access the myVar in the myJavaScript.js?

I have already tried the following things in my JavaScript file, neither of them worked for me

  1. var tempVar = "<%= session.getAttribute(\"myVar\") %>";
  2. var tempVar = "${myVar}";
  3. var tempVar = "<%=myVar%>"

Note: Tested solutions highly appreciated. Thanks.

Upvotes: 0

Views: 721

Answers (2)

Yilei
Yilei

Reputation: 269

In your JSP file, include the definition of the variable before you include your javascript file. If you are referring to a variable set earlier in the JSP file. You can do the following.

<script type="text/javascript">
    var var = "${var_name}";
</script>
<script src="js/myJavascript.js"></script>

In your JavaScript file, you can directly refer to the variable. In this case, you can refer to the variable as "var".

e.g.

alert(var);

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

Here's the code to get the value of myVar in javascript.

var tempVar="<%=pageContext.getAttribute("myVar")%>" />

Simillarly you can get all the values of variables using Page Context set on that JSP page.

Hope it helps.

Upvotes: 0

Related Questions