get jsp variable value in jquery

2

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

 <body>
       <%!  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"/>
            </div>

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
source

1 answer

1

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; %>
<script>
var miVar = <%= contador %>;
alert("El valor del contador es " + miVar);
</script>

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

$.ajax({
    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