get jsp variable value in jquery


How do I pass the value of a variable declared in a jsp to a js file to modify it and pass it back to the jsp.

jsp file

       <%!  int contador = 3; %>
        <div class = "container">
            <div  class="page-header page-header2 text-left">
                <img src="resource/img/logo.png" class="img-responsive " alt="Responsive image"/>

I need to change that value of the counter variable from a javaScript file with a jquery function

asked by Jeferson Martinez 16.08.2016 в 06:05

1 answer


To pass a variable from JSP to JavaScript and it can be used in the code, you just have to write it on the page inside a script tag:

<%!  int contador = 3; %>
var miVar = <%= contador %>;
alert("El valor del contador es " + miVar);

Then to pass the JavaScript variable to JSP you could use AJAX. That with jQuery it would be something like this:

    url: "mipagina.jsp",
    data: { contador: miVar }

But beware: this will pass the JavaScript data to JSP asynchronously. As far as I know, it can not be done in a synchronous way (execute JSP, in the middle of execution, do something in JavaScript, and continue with JSP). That would not be possible.

answered by 16.08.2016 в 13:54