2014-03-28 80 views
1

對不起,我知道這個問題在過去已經被問過了,但我沒有得到它的運行。任何人都可以告訴我,爲什麼我的代碼不工作?使用java腳本的gwt函數調用

我所嘗試的是:我想在HTML頁面中用java腳本調用gwt函數。 gwt函數創建一個int,返回它並且javascript應該在html頁面中解析它。

我的Java代碼:

package com.test.client; 

import com.google.gwt.core.client.EntryPoint; 

public class TestCode implements EntryPoint { 
    public static native void exportTestReturn()/*-{ 
    $wnd.testReturn = $entry(@com.test.client.TestCode::testReturn()); 
    }-*/; 

    public static int testReturn(){ 
    int testVar = 3; 
    return testVar; 
    } 

    public void onModuleLoad() { 
    exportTestReturn(); 
    } 
} 

而且我的html代碼:

<!doctype html> 
<html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>TestTitle</title> 
    <script type="text/javascript" language="javascript" src="com.test.TestCode/com.test.TestCode.nocache.js"> 
    </script> 
    </head> 

    <body> 
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe> 

    <p>Gwt html file tries to start gwt function and parse the return value</p> 
    <script> 
     document.write("JS output:" + testReturn() + "<br>"); 
    </script> 
    </body> 
</html> 

回答

0

看來你調用的函數之前它已被GWT onModuleload出口。

GWT使用的自舉腳本(your_app.nocache.js),其計算所述置換,然後加載該應用程序腳本(xxxx.cache.js)異步。

如果你從瀏覽器的javascript控制檯調用你的函數,你可以看到它的工作原理。

配置你的JavaScript代碼要等到GWT代碼已經滿載,或把它放在一個功能塊,並從JSNI方法調用它。

public static native void exportTestReturn()/*-{ 
    $wnd.testReturn = $entry(@com.test.client.TestCode::testReturn()); 
    $wnd.onLoad(); 
}-*/; 


<script> 
    function onLoad() { 
    document.write("JS output:" + testReturn() + "<br>"); 
    } 
</script> 

如果你願意等到GWT已經加載,在一個循環進入到其中任何一個GWT設置窗口中的對象加載時存在的變種,不過這是在一個非常棘手的解決方案:

<script> 
(function loopWaitGwtReady() {   
    setTimeout(function() { 
    if (window.__gwt_activeModules) 
     document.write("JS output:" + testReturn() + "<br>"); 
    else 
     loopWaitGwtReady() 
    }, 50) 
})();  
</script> 
+0

感謝您的快速回答,但它不適合我。如果我添加了'$ wnd.onLoad();',把單據行的功能就像你告訴我,我得到以下錯誤: '[錯誤] [com.test.TestCode]無法加載模塊入口點類com.test.client.TestCode(請參閱關聯的異常以瞭解詳細信息) com.google.gwt.core.client.JavaScriptException:(TypeError)@ com.test.client.TestCode :: exportTestReturn()([]):$ wnd.onLoad不是函數' – user3473355

+0

答案中有一個小錯字 - 它應該是函數onLoad(){',而不是'onLoad(){'。進行此更改將正確地聲明該函數,以便可以從GWT代碼中調用該函數。 –

+0

謝謝,多數民衆贊成在工作:-) 其他解決方案將如何實施?如何讓我的JavaScript代碼等待gwt代碼完全加載? – user3473355