在GWT中执行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>
答案 0 :(得分: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);
};
});
答案 1 :(得分: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();
}
}
它们有点陈旧但仅供参考:RequestBuilderUsage和GeetingResponse through GWT HTTP。
我希望以上几行能给出一些基本的想法