Reputation: 5875
I have some questions which are as follows:
How can I use the JSP variable/array in JQUERY code? Here what ever the JQUERY code we have is stored in separate .js file and that file is included in the JSP file.
Actually I want to initialize the JQUERY array with the JSP variable. So please guide me to achieve this task.
Upvotes: 5
Views: 29714
Reputation: 89189
In Plain Old JSP
<script>
var someText = "<%= myBean.getText() %>";
</script>
Using EL (Expression Language)
<script>
var someText = "${myBean.text}";
</script>
Using Struts
<script>
var someText = '<bean:write name="myBean" property="text" />';
</script>
Using JSTL
<script>
var someText = '<c:out value="${myBean.text}" />';
</script>
In essence, it's possible to populate Javascript objects from JSP. Don't forget that scriptlets and tags are just rendered back as HTML/XHTML, so JS cannot talk to tags and vice-versa.
Upvotes: 17
Reputation: 1109222
Java/JSP runs in webserver at the server machine and produces HTML/CSS/JS code. Server machine sends HTML/CSS/JS code to client machine. HTML/CSS/JS runs in webbrowser at client machine. Rightclick page and view source, you don't see any Java/JSP code.
JSP is a view technology which provides a template to write HTML/CSS/JS in and the ability to interact with backend Java data using taglibs/EL to control page flow and access data.
Whenever you want to let JavaScript access Java/JSP variables, all you need to do is to just write a Java variable as if it is a JavaScript variable.
<script>var foo = '${bean.foo}';</script>
Is an excellent example. Note that those quotes are required for JavaScript itself, not for JSP/EL. Imagine that ${bean.foo}
returns bar
, then the generated HTML/CSS/JS page which arrived at the client side would end up looking like:
<script>var foo = 'bar';</script>
Whenever you want to let Java/JSP access JavaScript variables, all you need to do is to let JavaScript fire a (XML)HTTP request. More background info and examples can be found in this article.
Upvotes: 2
Reputation: 7214
You can use this -
<input type="hidden" id="var1" value="<%=jspVar%>" />
and then use var1 in jQuery.
Upvotes: 0
Reputation: 262724
Not directly. You'd have to set it into the page somewhere.
<script>
var fromJsp = '${theVar}';
</script>
Note that this could get tricky for complex objects. Maybe JSON serialization can be your friend here.
Also note that this is one-way only. It is impossible to set the value of JSP variables from JavaScript (since the JavaScript runs client-side after the JSP has finished its work).
Upvotes: 0