Assign JavaScript variable to Java Variable in JSP

后端 未结 7 1399
猫巷女王i
猫巷女王i 2020-11-30 04:49

Ello there,

I\'m trying to assign the value of a javascript variable to a java variable. But I don\'t have clue how to do this? Say for example I have this:

相关标签:
7条回答
  • 2020-11-30 05:27

    The answer is You can't. Java (in your case JSP) is a server-side scripting language, which means that it is compiled and executed before all javascript code. You can assign javascript variables to JSP variables but not the other way around. If possible, you can have the variable appear in a QueryString or pass it via a form (through a hidden field), post it and extract the variable through JSP that way. But this would require resubmitting the page.

    Hope this helps.

    0 讨论(0)
  • 2020-11-30 05:27

    I think there's no way to do that, unless you pass the value of the JavaScript var on the URL, but it's a ugly workaround.

    0 讨论(0)
  • 2020-11-30 05:28

    JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.

    0 讨论(0)
  • 2020-11-30 05:28

    you cant do it.. because jsp is compiled and converted into html server side whereas javascript is executed on client side. you may set the value to a hidden html element and send to servlet in request just in case you want to use for further

    0 讨论(0)
  • 2020-11-30 05:32

    Java script plays on browser where java code is server side thing so you can't simply do this.

    What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server

    HTML

    <input type="hidden" id="hiddenField"/>
    

    make sure this fields lays under <form>

    Javascript

    document.getElementById("hiddenField").value=yourCalculatedVariable;
    

    on server you would get this as a part of request

    0 讨论(0)
  • 2020-11-30 05:32

    As JavaScript is client side and JSP is Server side.

    So Javascript does not execute until it gets to the browser, But Java executes on the server. So, Java does not know the value of the JavaScript variable.

    However you assign value of Java variable to JavaScript variable.

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