This mini tutorial shows you how to call Wicket from Javascript. It is based on an e-mail from Michael Sparer.
Setup the Wicket response to the Javascript call
Add the AbstractDefaultAjaxBehavior to the component you'd like to call from javascript. You then have to override the respond method of AbstractDefaultAjaxBehavior to perform your actions and to append your changes to the response
For example in your panel:
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() { protected void respond(final AjaxRequestTarget target) { target.add(new Label("foo", "Yeah I was just called from Javascript!")); } }; add(behave);
Add the calling Javascript to the page header
Any component can add Javascript to the page header by implementing IHeaderContributor, that's where the
response-object gets passed.
TODO: add an example of Java code.
Here is an example Javascript code:
function callWicket() { var wcall = wicketAjaxGet('$url$' + '$args$', function() { }, function() { }); }
'$url$' is obtained from the method behave.getCallbackUrl()
. If you paste the String returned from that method into your browser, you'll invoke the respond method, the same applies for the javascript method.
You can optionally add arguments by appending these to the URL string. They take the form &foo=bar
.
Obtaining the arguments
Ok, this is actually quite ugly, but you get the optional arguments in the response method like so:
Map map = ((WebRequestCycle) RequestCycle.get()).getRequest().getParameterMap();