我正在开发一个需要与通用web服务器通信的GWT web应用程序。不幸的是,服务器只支持PHP,所以我不能使用GWTRPC。这就是为什么我想在服务器端使用一个简单的PHP脚本,它以JSON格式返回所有必要的数据。因为我对GWT相当陌生,所以我的代码基于以下示例:
http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON
PHP脚本似乎运行良好。Firebug显示了返回的JSON数据和端口200:响应:
[{"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服务器上执行应用程序,不会出现异常,也不会弹出警报。通过使用一些警报(为了可读性,我在上面的代码中省略了这些警报),我注意到new RequestBuilder()中的try语句被执行了。(*)处的另一个警报显示,try语句已通过。(如前所述,没有例外)。显然,onResponseReceived()方法从未执行过。我从来没有调用过这个方法,所以这可能是我出现问题的原因。但是,我不明白应该在哪里调用onResponseReceived()。
备注:我省略了我的PHP脚本,因为这实际上与在线示例中显示的相同(http://code.google.com/p/google-web-toolkit-doc-1-5/wiki/GettingStartedJSON)。此外,剧本似乎运行正常。
你怎么知道onResponseReciveved没有被执行?当script.php返回JSON数据时,应该调用此函数。假设您的服务器发回一个200状态代码,则可能会解析响应,但不会对数据采取任何措施
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);
// Now what? hm isn't actually used for anything...
} else {
throw new JSONException();
}
从方法末尾返回的值来看,table
显然很重要,但在调用onResponseRecived回调之前,它将被返回,为空。这是因为所有GWTAjax调用都是异步的——在等待服务器恢复时,脚本不会停止运行。在if(jsonArray!=null)块中创建一个带有response.getTest()的警报,您可能会发现这段代码毕竟被调用了。如果是这样的话,那么您就成了That's not async的牺牲品了——这被认为是一种很好的JavaScript实践(在GWT中几乎是强制性的),即等待结果在准备好时到达,并在此期间保持正常执行。