How do I pass Javascript variable to and JSTL?

前端 未结 3 804
遥遥无期
遥遥无期 2021-01-06 13:59

How do I pass Javascript variable to and JSTL?



        
相关标签:
3条回答
  • 2021-01-06 14:32

    You need to send it as a request parameter. One of the ways is populating a hidden input field.

    <script>document.getElementById('firstName').value = 'john';</script>
    <input type="hidden" id="firstName" name="firstName">
    

    This way you can get it in the server side as request parameter when the form is been submitted.

    <jsp:setProperty name="emp" property="firstName" value="${param.firstName}" />
    

    An alternative way is using Ajax, but that's a completely new story/answer at its own.

    See also:

    • Communication between Java/JSP/JSF and JavaScript
    • Your previous question regarding the subject
    • Your other previous question regarding the subject

    If you can't seem to find your previously asked questions back, head to your user profile!

    0 讨论(0)
  • 2021-01-06 14:38

    AFAIK you can't send data from JavaScript to JSTL that way. Because the JSTL tags are handled serverside, so the <jsp:> tags will be parsed on the server and replaced by HTML. So the <jsp:> tags won't be a part of the response that is sent back to the client; it will consist only of HTML/text. Therefore you can't access the <jsp:> tags from JavaScript, because they won't exist in the document.

    Edit: sorry, the <jsp:> tags wasn't visible.

    0 讨论(0)
  • 2021-01-06 14:46
    <script>
    var name = "<jsp:getProperty name="emp" property="firstName" />";
    </script>
    

    The JSP code executes before the JavaScript so by the time the JavaScript gets processed the tag will be replaced with the contents of emp.firstName.

    0 讨论(0)
提交回复
热议问题