How to let JavaScript use the variable from server side? [duplicate]

只愿长相守 提交于 2019-12-29 09:45:09

问题


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

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