javascript to jsp

2019-09-20 17:37发布

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>

2条回答
祖国的老花朵
2楼-- · 2019-09-20 18:13

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!

查看更多
Deceive 欺骗
3楼-- · 2019-09-20 18:30

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:

查看更多
登录 后发表回答