2016-04-14 88 views

回答

3

看看Vaadin的

整合JavaScript組件和擴展

這裏:

https://vaadin.com/docs/-/part/framework/gwt/gwt-javascript.html#gwt.javascript.rpc

您可以創建一個JavaScript連接或組件,然後可以使用,使像RPC是如此:

@JavaScript({"mycomponent-connector.js"}) 
public class MyComponent extends AbstractJavaScriptComponent { 

    public MyComponent(){ 
     // when you create the component 
     // add a function that can be called from the JavaScript 
     addFunction("returnResponse", new JavaScriptFunction() { 
      @Override 
      public void call(JsonArray arguments) { 
       String response = arguments.getString(0)); 
       // do whatever 
      } 
     }); 
    } 

    // set up a way to make the request 
    public void makeRequest(String url) { 
     callFunction("makeRequest", url); 
    } 

} 

與JavaScript文件mycomponent-connector.js(使用XMLHttpRequest爲例):

window.com_example_mypackage_MyComponent = 
function() { 
    var connector = this; 

    // add a method to the connector 
    this.makeRequest = function(theUrl){ 
     var xmlHttp = new XMLHttpRequest(); 
     xmlHttp.onreadystatechange = function() { 
      if (xmlHttp.readyState == 4 && xmlHttp.status == 200) 
       connector.returnResponse(xmlHttp.responseText); 
      } 
     }; 
     xmlHttp.open("GET", theUrl, true); // true for asynchronous 
     xmlHttp.send(null); 
    } 
}; 

調用服務器端的方法MyComponent.makeRequest("myurl")將觸發makeRequest方法在客戶端上。當返回響應時,我們呼叫connector.returnResponse(xmlHttp.responseText)將其發送回服務器,並由MyComponent的構造函數中添加的"returnResponse"函數處理。

+0

我可能很愚蠢,但我喜歡當人們解釋如此詳細=) 謝謝你,感謝你的時間。 –

相關問題