Java EE server服务返回数据传递给Ajax的一些问题
protected void doGet(HttpServletRequest request
, HttpServletResponse response
) throws ServletException
, IOException
{
response
.setContentType("text/html;charset=UTF-8");
String json
="{\"number\":\"小明\",\"name\":\"男\",\"author\":\"8\",\"price\":\"5600\",\"Press\":\"人民日报\",\"ISBN\":\"2210\",\"img\":\"滑稽.jpg\",\"action\":10}";
System
.out
.print(json
);
}
首先 上面是Java server 里的系统生成的doGet方法这里我自定义了一个json字符串 通过print的方法输出到Java控制台
xhr
.onreadystatechange = function () {
if (xhr
.readyState
== 4) {
if (xhr
.status
== 200) {
var response
= JSON.parse(xhr
.responseText
);
endobj
.done(response
);
} else {
endobj
.fail(response
);
}
}
}
然后上面是JS的Ajax接收Java后台返回的数据的代码,但是出现了一个问题,浏览器控制台打印返回的xhr.responseText是空的。 百度了半天也没找到一个正常的解决方法,经过一番折腾发现是后台返回数据的问题。因为System.out.print的方法根本没办法吧数据告诉前端。
protected void doGet(HttpServletRequest request
, HttpServletResponse response
) throws ServletException
, IOException
{
response
.setContentType("text/html;charset=UTF-8");
String json
="{\"number\":\"小明\",\"name\":\"男\",\"author\":\"8\",\"price\":\"5600\",\"Press\":\"人民日报\",\"ISBN\":\"2210\",\"img\":\"滑稽.jpg\",\"action\":10}";
PrintWriter res
= response
.getWriter();
res
.append(json
);
res
.flush();
res
.close();
}
所以换了一个方法,如上和PHP echo语句效果一样直接打印到页面(Ajax异步访问 我们是看不到这个打印的界面的)之后就可以获取数据了。