如何从 Javascript 调用 GWT java 函数? [英] How to call GWT java function from Javascript?

查看:23
本文介绍了如何从 Javascript 调用 GWT java 函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以从 Javascript 调用 Java (GWT) 方法?从文档中也不清楚.此处的所有示例 http://code.google.com/intl/ru/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html 演示从 JSNI(不是 JS)函数调用 java 函数.

Is it possible to call Java (GWT) methods from Javascript? It is also unclear from documentation. All samples here http://code.google.com/intl/ru/webtoolkit/doc/latest/DevGuideCodingBasicsJSNI.html demonstrate calling java functions from JSNI (not JS) functions.

更新 1

这是一个Java代码:

Here is a Java code:

public class Test_GoogleWeb_JSNI_02 implements EntryPoint {
/**
 * This is the entry point method.
 */
public void onModuleLoad() {
}

public static void Callee() {
    Window.alert("Callee");
}
}

这是 html 中的来电按钮示例:

Here is caller button samples in html:

<input type='button' value='Call' onclick='Test02()'>

这里有一些我尝试过但没有奏效的功能:

And here are some functions I tried and which were not worked:

<script type="text/javascript">

    function Test01() {
        @com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee()();
    }

    function Test02() {
        com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee()();
    }


</script>

更新 2

以下有效.

Java 准备:

public void onModuleLoad() {
    Prepare();
}

public static native void Prepare() /*-{
    $doc.calleeRunner = @com.inthemoon.tests.client.Test_GoogleWeb_JSNI_02::Callee();
}-*/;

public static void Callee() {
    Window.alert("Callee");
}

来电者:

function Test03() {
        document.calleeRunner();
}

有更好的方法吗?

推荐答案

您的示例将不起作用,因为您正试图在某些外部脚本中使用 JSNI.如果您想从 external JS 调用某些内容,您需要使用此 问题 或使用 GWT 出口商一个>

your example is not going to work, since you are trying to use JSNI in some external script. If you want to call something from external JS you need to use approach described in this question or use GWT exporter

更新:

公开 GWT 内容的最安全方法是将调用包装在其他一些函数中.例如:

The safest way to expose the GWT stuff is to wrap invocation in some other function. For example:

    public native void expose()/*-{
    $wnd.exposedMethod = function(param){
         @com.my.MyClass::myFunction(*)(param);
    }
}-*/;

否则你可能会在生产模式下遇到一些奇怪的错误=)

Otherwise you might encounter some strange bugs in production mode=)

这篇关于如何从 Javascript 调用 GWT java 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆