这次做的项目是一个通过google API来实现图片搜索的web应用。该项目是由Servlet获得浏览器用户输入,通过googleAPI进行查询,获取google返回的json 字符串,最后返回给浏览器。
本来流程应该没有问题,浏览器端的提交和响应通过firebug来看也是正常的,但post函数中注册的callback function一直不能被调用,之前在Servlet中已经设定 response.setContentType=("application/json; charset=utf-8"); 经过N次调试后终于发现原来是我在Servlet中response给浏览器的值不对。
原来,之前我一直以为Servlet response给浏览器的json和以前的text/html一样都是字符串,所以我将获取的json字符串response给了浏览器。但实际上应该response的是一个JSONObject对象,或者是经过gson处理的String。
正确形式应该为:
try { JSONObject json = new JSONObject(buffer.toString()); resp.setContentType("application/json; charset=utf-8"); resp.setHeader("pragma", "no-cache"); resp.setHeader("cache-control", "no-cache"); PrintWriter out = resp.getWriter(); out.println(json); out.flush(); } catch (JSONException e) { e.printStackTrace(); }
或者使用gson将获取的String转换为格式正确的json 字符串
Gson gson = new Gson();
String jsonResult = gson.toJson(buffer.toString());
resp.setContentType("application/json; charset=utf-8");
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
PrintWriter out = resp.getWriter();
out.println(jsonResult);
out.flush();