我已经在很多地方研究过这个话题并找到了一些方法。在这个特定场景中,我使用https://cwiki.apache.org/confluence/display/WICKET/Calling+Wicket+from+Javascript文章作为参考。
我在Java中做了什么,
public class HomePage extends WebPage {
private static final long serialVersionUID = 1L;
public HomePage(final PageParameters parameters) {
super(parameters);
final AbstractDefaultAjaxBehavior behave = new AbstractDefaultAjaxBehavior() {
protected void respond(final AjaxRequestTarget target) {
target.add(new Label("foo", "Yeah I was just called from Javascript!"));
}
public void renderHead(Component component,IHeaderResponse response){
String componentMarkupId = component.getMarkupId();
String callbackUrl = getCallbackUrl().toString();
response.render(JavaScriptHeaderItem.forScript("var componentMarkupId='"+componentMarkupId+"'; var callbackUrl='"+callbackUrl+"';","values"));
}
};
add(behave);
}
}
和我的HomePage.html,
<!DOCTYPE HTML>
<html>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var wcall = Wicket.Ajax.get({ u: '${callbackUrl}' + '' });
alert(wcall);
});
</script>
</body>
</html>
我尝试做的是使用我初始化的变量调用get ajax方法。但是当我的页面加载时,在firebug控制台中说,
ReferenceError: Wicket is not defined
[Break On This Error]
var wcall = Wicket.Ajax.get({u:'$ {callbackUrl}'+''}};
这里出了什么问题?
还有其他从Javascript调用Java函数的好方法吗?
答案 0 :(得分:1)
您需要添加wicket javascripts添加到页面中,通常通过确保renderHead等覆盖方法进行super.renderHead调用。
答案 1 :(得分:0)
Wicket 6.x:在扩展AbstractDefaultAjaxBehavior的类中
@Override
public void renderHead(Component component, IHeaderResponse response) {
String callbackUrl = getCallbackUrl().toString();
StringBuffer script = new StringBuffer();
script
.append("var callbackUrl = '").append(callbackUrl).append("';\n")
.append("someJavaScriptCode();\n")
.append("Wicket.Ajax.get({u: callbackUrl});");
response.render(OnDomReadyHeaderItem.forScript(script.toString()));
}