I successfully implemented a way to call my Wicket 6 Java code from JavaScript using option A, as demonstrated in this example:
However, I am now facing the challenge of finding examples for returning data from the Java side back to JavaScript. The generated JavaScript callback function does not include a return statement. How can I accomplish this?
In clarification, I am not attempting to set an attribute in Java. Calling Wicket from JavaScript is not the issue at hand. My goal is to return a JSON object from Wicket to the browser as a result of an Ajax request.
Finding inspiration from martin-g's examples, I developed a functional implementation...
Java
public class MyAjaxBehaviour extends AbstractDefaultAjaxBehavior {
@Override
protected void onComponentTag(ComponentTag tag) {
super.onComponentTag(tag);
tag.put("aprachatcallbackurl", getCallbackUrl());
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.setDataType("json");
attributes.setWicketAjaxResponse(false);
}
@Override
protected void respond(AjaxRequestTarget target) {
getComponent().getRequestCycle().replaceAllRequestHandlers(
new TextRequestHandler("application/json", "UTF-8", "{...JSON GOES HERE...}));
}
}
JavaScript
var mySuccessCallback = function(param1, param2, data, statusText) {
// Data contains the parsed JSON object from MyAjaxBehaviour.respond(...)
...
}
var myFailureCallback = function() {
...
}
Wicket.Ajax.get({
"u": callbackUrl,
"dt": "json",
"wr": false,
"sh": [mySuccessCallback],
"fh": [myFailureCallback]
});
The main issue lies in the fact that the Wicket 7 Reference incorrectly advises to use "wr" instead of "dt" in the JavaScript call. :)