user608032
user608032

Reputation: 3

call a method in Javascript file

in a Struts 2 based application i have Java classes and JSPs. in the JSPs i have included Javascript files.
i have a Java method which return a string.
i want to call this method in the Javascript files.
how can I do this?

Upvotes: 0

Views: 1460

Answers (4)

Quaternion
Quaternion

Reputation: 10458

Do you mean something like the following in your JSP?

<script type="text/javascript">
    <s:property value="JSMethodName"/>();
<script>

I mean the above will call a particular JS method once... you could even wrap that <s:property> tag in an iterator to call a number of methods... probably better to modify the above for after page load.

If the above is not sufficient you can use ajax methods to return a list of JS methods dynamically and invoke them... for that I would advise using the jquery and the S2 JSON plugin.

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168825

You can write the Java/JSP string directly into the body of the page as a JS variable. (If I understand you correctly, and I am not sure I do).

Upvotes: 1

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17435

You mean either one of two things.

Either you want to call the method at render time, and include the output in your Javascript. For that, call the method using JSP.

Or you want to call the method at 'runtime'. If so, you need to do an ajax call from the browser, and call the method that way. You could use different techniques for that (jax-rs comes to mind). Maybe struts already has something; not sure about that. Basically, you make an http request towards a servlet. The servlet calls your method and returns the response. Then your javascript handles the response.

Upvotes: 0

Quentin
Quentin

Reputation: 943214

Struts is a server side framework, so your Java is running on your server.

JavaScript is usually found running in the browser (and it doesn't sound like you have involved any SSJS solution).

Therefore: You can't. The programs are running on different computers and can't interact directly.

You would need to issue a new HTTP request, including the data somewhere it can be retrieved (e.g. in a query string). You could do this by setting location, generating a <form> and calling its submit() method, using the XMLHttpRequest object, dynamically adding a <script> element with the src set appropriately and various other approaches.

Upvotes: 2

Related Questions