javascript to jsp

空扰寡人 提交于 2019-12-13 08:27:00

问题


How to show a javascript 'var' in my jsp?

 ...
 <script type="text/javascript">
 ... // My code to get the value. 
 var val = combo.getValue(); 
 </script>
 <body>
 The value is : //to be displayed here
 </body>

回答1:


Add a HTML element which should mark the place where the value is to be displayed and give it an id.

<body>
    The value is : <span id="value"></span>
</body>

Then let your JS access it by document.getElementById() and modify its inner HTML.

document.getElementById("value").innerHTML = val;

You only need to ensure that the particular script executes after the HTML page has loaded. Do it during window.onload or put the <script> at end of <body> or wrap it in a function which you execute on some event.

As to the JSP part, this is not relevant here. All JSP does is generating and sending HTML/CSS/JS code from webserver to webbrowser. JavaScript knows nothing about JSP, all it can see and access is HTML/CSS which you can also see by rightclicking the page in webbrowser and choosing View Source.

See also:

  • Communication between Java/JSP/JSF and JavaScript



回答2:


You need to place it somewhere so it could be pushed to your JSP page. A hidden field is a good option:

 <script type="text/javascript">
 ... // My code to get the value. 
 document.getElementById("nn").value = combo.getValue();
 ... you could submit the form here if you want
 </script>
 <body>
 The value is : //to be displayed here
 <form action="yourjsp.jsp" method="get">
     <input type="hidden" id="nn"/>
 </form>
 </body>

Other possibility might be using AJAX.

One way or another, I would suggest you reading a little bit more on general topics about Web Applications to differentiate JSP/JavaScript/POST/GET/CSS/HTML and other basic concepts.

Good luck!



来源:https://stackoverflow.com/questions/4886229/javascript-to-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!