GWT:从Java调用javascript函数

时间:2014-12-02 03:24:45

标签: java javascript gwt libgdx

您好我正在尝试从java调用.js文件中的函数。

在我的Java代码中我有

@Override
public native void test()
/*-{
    //JAVASCRIPT
    $wnd.h8();
}-*/;

该方法内部只是一个提醒,但我无法调用我的一个功能。我尝试过$ wnd,$ doc,没有。

说我有一个带有这个的functions.js:

function h8(){
    alert("hi");
}

在我的索引中我有:

<!doctype html>
<html>
       <head>

              <title>GWT Test</title>
              <meta http-equiv="content-type" content="text/html; charset=UTF-8">
              <link href="styles.css" rel="stylesheet" type="text/css">
              <script src="js/functions.js"></script> 

       </head>

       <body>
              <div align="center" id="embed-html"></div>
              <script type="text/javascript" src="html/html.nocache.js"></script>
       </body>

</html>

所以你看到我在html中加载脚本文件,但我得到的是'undefined不是函数&#39;错误。没有$ doc或$ wnd我就得不到变量h8错误。

这是控制台错误:

GwtApplication: exception: (TypeError) 
 line: 112978
 column: 10
 sourceURL: http://127.0.0.1:9876/html/52574FB8FF8725CA72DFF813B62FEE86.cache.js
 __gwt$exception: <skipped>: undefined is not a function (evaluating '$wnd.h8()')
(TypeError) 
 line: 112978
 column: 10
 sourceURL: http://127.0.0.1:9876/html/52574FB8FF8725CA72DFF813B62FEE86.cache.js
 __gwt$exception: <skipped>: undefined is not a function (evaluating '$wnd.h8()')

1 个答案:

答案 0 :(得分:3)

您应该定义Window函数:

Window.h8 = function() {
    alert("!!!");
};

并使用$和。

访问它
private static native void callFunction() /*-{
    $wnd.h8();
}-*/;