我正在研究需要与常用Web服务器通信的GWT Web应用程序。不幸的是,服务器只支持PHP,所以我不能使用GWT RPC。这就是为什么我想在服务器端使用一个简单的PHP脚本,它以JSON格式返回所有必要的数据。由于我对GWT相当陌生,因此我的代码基于此示例:
http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON
PHP脚本似乎正常工作。萤火虫显示我返回的JSON数据和所述端口200: 响应:GWT:提交http请求后处理JSON数据
[{"key1":"k1","value1":"v1"},{"key2":"k2","value2":"v2"},{"key2":"k3","value3":"v3]
然而,该响应被从未处理进一步。这里是我的代码:
private static final String JSON_URL = "http://www.myUrl/myScript.php";
public HashMap<String, Integer> loadCalendarTable(String p1, String p2) {
table = new HashMap<String, Integer>();
String url = JSON_URL+"?p1="+p1+"&p2="+p2;
url = URL.encode(url);
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
Window.alert("Couldn't retrieve JSON");
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
try {
// parse the response text into JSON
JSONValue jsonValue = JSONParser.parse(response.getText());
JSONArray jsonArray = jsonValue.isArray();
if (jsonArray != null) {
HashMap<String, Integer> hm = updateTable(jsonArray);
}
else
throw new JSONException();
}
catch (JSONException e) {
Window.alert("Could not parse JSON");
}
}
else
Window.alert("Couldn't retrieve JSON (" + response.getStatusText() + ")");
}
});
//(*)
}
catch (RequestException e) {
Window.alert("Couldn't retrieve JSON");
}
return table;
}
private HashMap<String, Integer> updateTable(JSONArray array) {
//do something
return table;}
通过在web服务器上执行应用程序,不会发生异常并且不会弹出警告。通过使用一些警报(我在上面的代码中为了可读性而省略),我注意到在新的RequestBuilder()中的try语句被执行。 (*)的另一个警报显示try语句已通过。 (没有例外发生,如前所述)。显然,onResponseReceived()方法从不执行。我从来没有称这种方法,所以这可能是我的问题的原因。但是,我不明白我应该在哪里调用onResponseReceived()。
备注: 我省略了我的PHP脚本,因为这实际上与在线示例(http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON)中显示的相同。此外,脚本似乎正常工作。
你是对的。该值在调用onResponseReceived回调之前返回空值。我没有注意到我的测试结果。非常感谢你! – 2012-03-20 20:46:32