1

How do I pass the JSP variable to javascript function in external file?

I have the following set up

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript" src="js/jquery/jquery-2.1.1.js"></script>
<script type="text/javascript" src="js/jquery/ui/jquery-ui.js"></script>
<script type="text/javascript" src="js/date/moment.js"></script>
<script type="text/javascript" src="js/app.js"></script>
<script type="text/javascript" charset="utf-8"  src="js/d3.js"></script>
<script type="text/javascript" src="js/myScript.js" ></script>
<link href="js/jquery/ui/jquery-ui.css" rel="stylesheet" />
<link href="js/jquery/ui/jquery-ui.theme.css" rel="stylesheet" />
<link href="css/myCSS.css" rel="stylesheet" />
<title>My Title</title>
</head>
<body>
   <div id="myDIV">
      <c:set var="myVar" value="${myInVar}" />
      <script>runMyScript();</script>
   </div>
</body>
</html>

Now inside my javascript, I try to access the jsp variable but neither of the two ways I found online works:

var javaScriptVar = '${myVar}';
var javaScriptVar2 = "<%=myVar%>";

Instead of the actual value of the jsp variables, I get the strings.

I read in this answer: Passing variable from JSP to Javascript which suggest to declare the variables before I include the javascript file, but I can't figure out how to do that.

If I put them in the header, they are not resolved because they come from a backend request. If I don't include the script in the header and add src attribute to the script section before making the call, the method is never executed.

Totally confused here.

2
  • what do you mean by 'I get the strings.'? What is the actual output you get. Commented Dec 8, 2016 at 22:04
  • I mean the string is not evaluted, it's just a string. The value ends up being "<%=myVar%>" Commented Dec 8, 2016 at 22:10

1 Answer 1

2

Your JavaScript is inside a .js file. The server will (exceptional circumstances aside) treat that as a static file. It will just serve it up to the client without processing.

If you want to run JSP code (such as <%=myVar%>) then put it in a JSP file.

Sign up to request clarification or add additional context in comments.

2 Comments

Both the body and header are in JSP files.
I think I see what you mean. JSP is not evaluated in the external file, so pass them into the function in the external file.

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.