Skip to content Skip to sidebar Skip to footer

Jsp : Using Java Variable In Javascript

I have a JSP page called index.jsp. I have a Java variable called totalCount inside this page : <%= int totalCount = getTotalCount();%> Now I want to use this variable in Ja

Solution 1:

Just assign the value to your Javascript variable.

<scripttype="text/javascript">var count = '<%= totalCount %>';
</script>

But using scriptlets been highly discouraged and shift to JSTL as soon as possible.

Read : How to avoid Java code in JSP files?

As others pointed out, do not create unnecessary hidden elements on DOM. If you really want to use this variable across files declare this variable on top. Even before script includes, so that it avail across all the files.

Example:

<scripttype="text/javascript">var count = '<%= totalCount %>';
    </script><scripttype='text/javascript'src='js/blah.js'></script><scripttype='text/javascript'src='js/blahblah.js'></script>

Solution 2:

Just create a hidden field on your HTML page and access that value using JavaScript.

HTML

 <inputid='hdn-total-count'type='hidden' value='<%=totalCount%>' />

JavaScript

var totalCount = document.getElementById('hdn-total-count').value;

jQuery (Cross browser compatible)

var totalCount = $('#hdn-total-count').val();

All of the other answers are going to work on inline and on-page JavaScript. But they are not going to work for JavaScript in external files (which are cacheable).

Solution 3:

simply you can use

<scripttype="text/javascript">var xyz=<%=  getTotalCount();%>
</script>

But I dont recommend you to use java codes inside JSP.Please look for JSTL

Solution 4:

you can write a code something like this. But it's not a clean way of doing it. Why do you want to do it? You can do it via AJAX calls.

Here is the sample code

<sciprt type="text/javascript">
  var myVariable = <%=request.getAttribute("rep");%>
</script>

Post a Comment for "Jsp : Using Java Variable In Javascript"