【问题标题】:GWT: Calling a javascript function from JavaGWT:从 Java 调用 javascript 函数
【发布时间】:2014-12-02 03:24:44
【问题描述】:

您好,我正在尝试从 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 中加载脚本文件,但我得到“未定义不是函数”错误。如果没有 $doc 或 $wnd,我会收到 Can't find variable 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()')

【问题讨论】:

  • 如果你在 JS 控制台中调用 h8() 会发生什么?我想你正在这样做,但你能检查一下你是否在入口点调用了 test() 方法吗?
  • test() 是从 java 中调用的,因为如果我将 $wnd.h8() 更改为一个简单的警报(“hey”),它就会发出警报。
  • 你没有回答我的第一个问题 h8 在开发控制台中是否有效。我猜你是在其他范围内定义。
  • 已修复。谢谢你:)

标签: java javascript gwt libgdx


【解决方案1】:

你应该定义窗口函数:

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

然后用 $wnd 访问它。

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

【讨论】:

  • 我调用 $wnd.h8();来自 Java 测试方法并具有 Window.h8 = function(){ alert("hi"); };在我的 js 文件中,仍然 undefined 不是函数... [gwt$exception: : undefined is not a function (evalating '$wnd.h8()']
  • 它是小写的window.h8。谢谢你们。
猜你喜欢
  • 1970-01-01
  • 2012-01-27
  • 2012-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2011-07-24
相关资源
最近更新 更多