Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a servlet variable into javascript

I'm looking to pass a servlet variable, myVar that is passed into a JSP page, and pass it to JavaScript. The JavaScript is an external javascript that is included into the JSP page.

I have a button that calls the JavaScript function, but I'm unable to pass any of the variables that are passed into the JSP page through the servlet. The button is not a part of a form.

I've tried in a function in JavaScript to call:

var x = '<%=myVar%>';

AND

var x = '${myVar}';

AND

var x = '<%= (String)request.getParameter("myVar") %>';

However, x is always a string of what I inputted.

I'm not using AJAX or JQuery. Any ideas?

Example Code is a simplified version: (so the button is actually a drop down that calls the js when I change the value, however, I want other variables that are not part of the drop down to be called in changeCLass)

Servlet side:

request.setAttribute("otherVars","tests");

JSP:

<script type="text/javascript" src="external.js"></script>

<select name="vars" id="myVars" onchange="changeClass(this)">
<option value='1' selected="selected">1</option>
</select>

external.js included in JSP:

function changeClass(newVarX) {

    var newVarId =newVarX.value;
    var tID = '${otherVars}';

    alert(newVarId + " " + tID);
}

Output: 1 $(otherVars}

but output should be: 1 tests

like image 756
user1798546 Avatar asked Nov 04 '12 19:11

user1798546


1 Answers

This does not work, because your JavaScript file is not processed by the server. Possible solutions are:

  • Declare the variable tID globally in the JSP file.

    JSP:

    <script type="text/javascript" src="external.js"></script>
    <script type="text/javascript">
        var tID = '${otherVars}';
    </script>
    
    <select name="vars" id="myVars" onchange="changeClass(this)">
        <option value='1' selected="selected">1</option>
    </select>
    

    JavaScript (external.js):

    function changeClass(newVarX) {
        var newVarId = newVarX.value;
        alert(newVarId + " " + tID);
    }
    
  • Have the JavaScript file also be processed. You may use a JSP file for the JavaScript and apply the correct content type:

    JSP:

    <script type="text/javascript" src="external.jsp"></script>
    
    <select name="vars" id="myVars" onchange="changeClass(this)">
        <option value='1' selected="selected">1</option>
    </select>
    

    JavaScript (external.jsp --> note, that it's a JSP file, too, but the content type is set to text/javascript):

    <%@ page language="java" contentType="text/javascript; charset=UTF-8" pageEncoding="UTF-8"%>
    function changeClass(newVarX) {
        var newVarId = newVarX.value;
        var tID = '${otherVars}';
        alert(newVarId + " " + tID);
    }
    
like image 184
Jan Avatar answered Oct 22 '22 19:10

Jan