尽管您可以使用 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);
};
});