Reputation: 359
I'm trying to call a JS function embedded inside a JSP file from a servlet. I need to pass some arguments to the JS function. Will I be able to do that?
Upvotes: 2
Views: 4420
Reputation: 1794
Yes. You have 2 options:
1) Call desired Java functionality using AJAX (mostly used when user do some action):
$.ajax('/url/to/your/servlet', {data: 1, another-data: 2}, function() {
// success callback
});
2) Call desired JavaScript function when page is parsed or when it is loaded (prepare the call in JSP page). It is not direct call of JavaScript function from JSP, you just prepare the call and call is performed when page is parsed/loaded on the client side:
<script>
// Alert is show when page is parsed
alert(${data});
$(document).ready(function() {
// Alert is show when page is loaded (except of images and few other resources)
alert(${data});
});
</script>
Upvotes: 1
Reputation: 803
There is no reason why you should not be able to do that. However, note that the JS function will be executed in the client side. For example
<input type="text" name="user" onclick="submitName(this)"/>
can be part of a JSP and will be rendered as part HTML in the response. When the text field is clicked, the submitName() JS function will execute.
Note - This was to just illustrate that JS function call can be embedded in JSP , better way to bind events to HTML elements is to use frameworks like JQuery.
Upvotes: 1