1

在 GWT中执行 a 的正确方法是RequestBuilder什么能够完全按照纯 HTML 执行此操作:

<form action="javascript:;" method="post" data-field="form">
      <input class="rounded" name="username" size="20" type="text" data-field="username">
      <input class="rounded" name="password" size="20" type="password" data-field="password">
      <button class="submit" type="submit" value="Login" data-field="button"><br>
</form>
4

2 回答 2

3

尽管您可以使用 gwt 小部件包装每个输入,但在大型表单的情况下,最好遍历所有表单元素,读取它们的名称和值,并生成一个查询字符串以使用您的 requestBuilder 作为数据发送,此代码应该可以工作:

  String payload = "";
  Element e = DOM.getElementById("form");
  // you need make this recursive if you want grand-children
  for (int i = 0, l = e.getChildCount(); i < l; i++) {
    Element c = e.getChild(i).cast();
    if (c.getTagName().toLowerCase().matches("input")) {
      String name = c.<InputElement>cast().getName();
      String value = c.<InputElement>cast().getValue();
      payload += name + "=" + value + "&";
    }
  }

  RequestBuilder b = new RequestBuilder(POST, "/my_servlet");
  try {
    b.sendRequest(payload, new RequestCallback() {
      public void onResponseReceived(Request request, Response response) {
         String resp = response.getText();
      }
      public void onError(Request request, Throwable exception) {
      }
    });
  } catch (RequestException ex) {
    ex.printStackTrace();
  }

但是,我更喜欢使用gwtquery的口号:(do more, write less):

  Properties data = Properties.create();
  // This loop also gets grand-children, and you can use more sophisticated css selectors
  for (Element e: $("form").find("input").elements()) {
    data.set($(e).attr("name"), $(e).val());
  }

  GQuery.post("/my_servlet", data, new Function(){
    public void f(){
      // Use getDataObjet in non snapshot versions
      String response = arguments(0);
    };
  });
于 2013-04-12T20:43:30.253 回答
2

首先构建如下请求(伪代码):

RequestBuilder req= new RequestBuilder(RequestBuilder.POST, url);
req.setHeader("Content-Type","application/x-www-form-urlencoded");


StringBuilder sb = new StringBuilder();
sb.append(URL.encodeComponent("usename="+usernameVal+"&"));
sb.append(URL.encodeComponent("password="+passwordval));//add & if more params.


req.setRequestData(sb.toString());
req.setCallback(new RequestCallback() {

        @Override
        public void onResponseReceived(Request request, Response response) {
           //TO DO
        }

        @Override
        public void onError(Request request, Throwable exception) {
        }
    });

在提交按钮单击处理程序:

try {
       req.send();
    }
catch (Exception e){
       e.printStackTrace();

    }
}

它们有点旧,但仅供参考:RequestBuilderUsageGeetingResponse through GWT HTTP

我希望以上几行能给一些基本的想法

于 2013-04-12T19:34:27.460 回答