We have jsp, which uses some java beans to create some variables to be used inside jsp. I am wondering how to share those variables with javascript?
-
do you need the value changed on server side reflected on client aswell or just load time value ?Jigar Joshi– Jigar Joshi2013-01-15 22:42:00 +00:00Commented Jan 15, 2013 at 22:42
-
Variable is an ambiguous term in this context. You need to serialize the data to a form that can be rendered as a string and interpreted by a script in the browser. How you do that depends on the complexity of the data. It would also help if you stated the technologies and versions in play.McDowell– McDowell2013-01-15 22:50:02 +00:00Commented Jan 15, 2013 at 22:50
Add a comment
|
2 Answers
Write out your bean value to an HTML element's value or an attribute of the HTML element. Give the HTML element an ID. Use Javascript to retrieve the element by ID, or by another accessor, and you can access the value. Are you using struts or another Servlet framework?
A simple example
JSP:
<div id="employeeName">
<jsp:getProperty name="employee" property="firstName"/>
</div>
HTML:
<script type="text/javascript">var el = document.getElementById("employeeName");</script>
1 Comment
Adam Lee
I am just using pure servlet
You can use JSTL tags to output your Bean Values in JavaScript code. It's far from been elegant, but it works. For example, this is a fragment of a JSP page:
<script type="text/javascript">
<c:if test="${imServerSideBean eq false}" >
var imAJSVariable= new Object();
</c:if>
//More code here
</script>
<html>
//Code continues
You're using JSTL to select make visible a JavaScript variable or not.
2 Comments
Luiggi Mendoza
It's a bad idea to promote the usage of scriptlets. Refer to: How to avoid Java Code in JSP-Files?
Carlos Gavidia-Calderon
The example is using JSTL, but I'll delete the Scriptlet reference as suggested