我正在运行一个简单的网站,该网站使用ajax和jquery与TestServlet通信。servlet使用doGet((提供一个JSON对象,如下所示:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json = "{"name": "jsontest","type":"jsonobject"}";
response.getWriter().append(json);
}
当按下页面上的按钮时,会发出如下ajax请求:
$.ajax({
type: "GET",
url: "test",
data: "",
dataType: "json",
success: function(reply) { window.alert("Successn"+reply); },
error: function(err) { window.alert(err); }
});
请求成功,但reply
为空,我从web控制台获得:
XML Parsing Error: not well-formed
Location: http://localhost:8585/web/test
Line Number 1, Column 1: {"name": "jsontest","type":"jsonobject"}
我尝试指定mimeType: "applicationjson"
,但得到了相同的行为。相反,当我没有指定dataType
或放入contentType: "json"
时,我成功地正确读取了JSON字符串,但仍然得到了XML Parsing Error
。
有人能解释为什么我在假设交换JSON时会出现XML解析错误吗
注意:我使用的是Firefox和Tomcat9。
提前谢谢。
简单地说,我发现虽然我期望通过dataType
在请求中包含json内容,但servlet并没有指定其响应也使用该类型进行编码。添加:
response.setContentType("application/json");
解决了问题。