我正在尝试使用Java检索javascript变量.我认为我已经接近解决方案.
我想在面板上检索元素的宽度.为此,我在面板中添加了一个行为,该行为添加了回调并检索了参数(宽度和高度).
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()));
}
}
在javascript中,以下代码被调用:
function callbackWicketNewImage(element) {
var wcall = Wicket.Ajax.get({ 'u': 'callbackUrl', 'ep' : {'width': element.width(), 'height': element.height()}});
}
调用js代码时,将调用’respond’方法,但width和height参数的值未更改.他们仍然是“ undef”.
解决方法:
我用以下代码解决了我的问题.请注意,抽象的onResponse方法用于抽象目的.
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);
}
行为调用:
add(new SizeBehavior() {
@Override
public void onResponse(double width, double height) {
//set vars..
widthVar = width;
heightVar = height;
}
});