I have managed to call my Wicket 6 Java code from Javascript using option A in this example: https://stackoverflow.com/a/42612027/1047418
However, I have not been able to find examples for returning data from the Java side back to JavaScript (the generated JavaScript callback function does not even include a return statement). How can this be achieved?
Edit: I am not trying to set an attribute in Java and as I've already explained, calling Wicket from JavaScript is not the problem here. I am trying to return a JSON object from Wicket back to the browser as a result of an Ajax request.
Edit2: Following martin-g's examples I cobbled up this working example...
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]
});
Main problem as that the Wicket 7 Reference incorrectly instructs to use "wr" instead of "dt" in the JavaScript call. :)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…