I am trying to retrieve a javascript variable using Java. I think that I am close to the solution.
I want to retrieve the width of an element on my panel. To achieve this, I added a behavior to my panel that adds the callback and retrieves the parameters (width and height).
private class ImageBehavior extends AbstractDefaultAjaxBehavior {
@Override
protected void respond(AjaxRequestTarget target) {
//I receive a JavaScript call :)
StringValue width = getRequest().getRequestParameters().getParameterValue("width");
StringValue height = getRequest().getRequestParameters().getParameterValue("height");
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getExtraParameters().put("width", "undef");
attributes.getExtraParameters().put("height", "undef");
}
@Override
public void renderHead(Component component, IHeaderResponse response) {
super.renderHead(component, response);
response.render(OnDomReadyHeaderItem.forScript(getCallbackScript().toString()));
}
}
In javascript, the following code gets called:
function callbackWicketNewImage(element) {
var wcall = Wicket.Ajax.get({ 'u': 'callbackUrl', 'ep' : {'width': element.width(), 'height': element.height()}});
}
When the js-code is called, the 'respond' method gets called but the values of the width and height parameter did not change. They remained 'undef'.
I fixed my problem with the following code. Please note that the abstract onResponse method is for abstraction purposes.
public abstract class SizeBehavior extends AbstractDefaultAjaxBehavior {
@Override
protected void respond(AjaxRequestTarget target) {
IRequestParameters request = RequestCycle.get().getRequest().getRequestParameters();
onResponse(request.getParameterValue("widthParam").toDouble(),
request.getParameterValue("heightParam").toDouble());
}
@Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
attributes.getDynamicExtraParameters()
.add("return {'widthParam': $(" + getComponent().getMarkupId() + ").width(), " +
"'heightParam': $(" + getComponent().getMarkupId() + ").height()}");
}
public void renderHead(Component component, IHeaderResponse response) {
response.render(OnLoadHeaderItem.forScript(getCallbackScript().toString()));
}
public abstract void onResponse(double width, double height);
}
Behavior call:
add(new SizeBehavior() {
@Override
public void onResponse(double width, double height) {
//set vars..
widthVar = width;
heightVar = height;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With