问题
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?
回答1:
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>
回答2:
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.
来源:https://stackoverflow.com/questions/14348265/how-to-let-javascript-use-the-variable-from-server-side