In my html, I need a开发者_JS百科 property from my bean and store it in a variable - how can I do this?
What I'm trying to do is, display an error message when a user's login fail - I know I can do this with javascript, but I don't know how I can "call" this javascript to load when a login is unsuccessful.
Many ways to do this.. but I don't know how to do any of them.
Like HTML and CSS, JS is part of template text. Just let JSP print it as if it is a JS variable.
<script>var foo = '${bean.foo}';</script>
You just need to make sure that the generated HTML looks the way so that JS understands it.
<script>var foo = 'bar';</script>
With JSP/JSTL/EL you can control the output whatever way you want. You can use JSTL <c:if>
to print it conditionally. You can use EL conditional operator ${condition ? printIfTrue : printIfFalse }
to toggle output based on a condition. Etcetera.
See also:
- Communication between Java/JSP/JSF and JavaScript
You can use @BalusC's way, but if you don't want to place <script>
tag in your JSP code, one option is to set the value as a hidden field:-
<input id="foo" type="hidden" value="${bean.foo}" />
Then, in your javascript, do this:-
var foo = document.getElementById("foo").value;
精彩评论