0

Can we initialize JavaScript variables with java in jsp page? like,

<script type="text/javascript">
var refreshId = setInterval(function() {
    var nv=<% out.print(num_voted); %>;
    var tv=<%out.print(totalvoted); %>;
    var m=<% out.print(month);%>;
    var y=<% out.print(year);%>;
    alert("refreshed");
    $('#alertmessagebox').text("Total members voted "+nv+" out of "+tv+" for "+m+" " +y);
}, 9000);
$.ajaxSetup({ cache: false });
 </script>

Code is not working as expected. :(

Is there way to do this? Why it is not possible by this way? shall we need to create header to do this?

6
  • 5
    What is output at browser. Can you please view source of generated page and paste result? Commented Sep 29, 2012 at 18:20
  • 2
    "not working as expected" is never enough information. You should say what you expected, and what actually happened. Commented Sep 29, 2012 at 18:29
  • What is out? Is that the same channel to which the static template content is written? Commented Sep 29, 2012 at 18:37
  • yes correct.. what i want to do is to make ajax request to a same page after certain interval. get some updated vales and assign them to javascript variables. here, the script is on the same page to which i want to make request.in above code sample i have not made any request to a page. mistake. sorry if i am not explaining well enough. Commented Sep 29, 2012 at 18:50
  • What are num_voted, totalvoted, month, year? Are they request parameters, attributes, scriptlet variables, ..? Commented Sep 29, 2012 at 19:39

1 Answer 1

1

Here is an example of setting Javascript variables in a JSP.

<head>
<%
    String numVotedStr = request.getParameter("numvoted");
    int numVoted = 0;
    if (numVotedStr != null) {
        numVoted = Integer.parseInt(numVotedStr);
    }
%>
<script type="text/javascript">
    function setInterval() {
        alert("hello " + <%= numVoted %>);
    }
</script>
</head>

<body>
<form>
    <input type="button" onclick="setInterval()" value="Press Me"/>
</form>
</body>
</html>

To test, use the appropriate version of this URL:

http://localhost:8080/sandbox/example.jsp?numvoted=99

This will popup an alert box with the integral value of "numvoted" on the HTTP request, by producing an HTML page where the value is initialized in Javascript. (The code should have at least a try-catch for the parseInt() call, but this will serve as simple example.)

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

1 Comment

Perhaps some kind of JSON encoding should be demonstrated, to avoid XSS - in case the OP's values aren't all int values.

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.