I am trying to convert a javascript variable to a jsp variable like this
var correct=9;
<%int correct1%>=correct;
But it gives syntax error.
I am trying to convert a javascript variable to a jsp variable like this
var correct=9;
<%int correct1%>=correct;
But it gives syntax error.
You can set a data in your JavaScript code from JSP, but not reverse. Something like this:
var correct = <% int correct1 = 1; out.println(correct1); %>;
If you want to transfer JavaScript variable's value to the server side, you have to do It only with form data posting or ajax.
Sample:
HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var correct = 9;
$.ajax({
url: 'your_jsp_file.jsp?correct=' + correct,
method: 'get',
success: function(result) {
alert(result);
}
});
</script>
JSP file (your_jsp_file.jsp):
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%
int correct1;
if (request.getParameter("correct") == null) {
out.println("error");
}
else {
String param = request.getParameter("correct");
if (param.matches("^[0-9]+$")) {
correct1 = Integer.parseInt(param);
}
out.println("ok");
}
%>