javascript - To invoke java function from velocity template during onclick event -
web application uses struts2 , velocity
1)
the velocity file has link , when link clicked want java function called.
productform.vm
<a href="javascript:void(0);" onclick="*************" id="acnt_link"> add acnt </a>
when link velocity file clicked, need java function called
abc.java
public void printabc(){ syso("java function called when link velocity temp clicked"); }
please advise on how this
2)
i can invoke javascript function when link velocity clicked, javascript function how can call java function(for example abc.printabc())
please advise.
you can take @ dwr gives methods java javascript function. directly taken tutorial:
public class remote { public string getdata(int index) { ... } }
and correspondening html snippet:
<head> <!-- other stuff --> <script type="text/javascript" src="[webapp]/dwr/interface/remote.js"> </script> <script type="text/javascript" src="[webapp]/dwr/engine.js"> </script> <script> function myremotemethod() { remote.getdata(42, { callback: function(str) { alert(str); }}); } </script> </head> <body> <!-- ... --> <a href="javascript:void(0);" onclick="myremotemethod()">add acnt</a> <!-- ... --> </body>
make sure integrate dwr struts, have tutorials that: dwr struts tutorial.
another solution call java method via ajax request:
function myremotemethod() { $.get('/link/to/method/') .done(function (data) { alert('return message of server was:' + data); }); }
this jquery example, make sure have library in <head>
of html code. call method in html code , "call" java method via ajax.
<a href="javascript:void(0);" onclick="myremotemethod()">add acnt</a>