2016-04-14 154 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

我可能很愚蠢,但我喜欢当人们解释如此详细=) 谢谢你,感谢你的时间。 –

相关问题