我正在研究需要與常用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