Reputation: 73
I am running a simple website that communicates with a TestServlet using ajax and jquery. The servlet gives a JSON object using doGet(), as follows:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json = "{\"name\": \"jsontest\",\"type\":\"jsonobject\"}";
response.getWriter().append(json);
}
When a button is pressed on the page, an ajax request is issued as follows:
$.ajax({
type: "GET",
url: "test",
data: "",
dataType: "json",
success: function(reply) { window.alert("Success\n"+reply); },
error: function(err) { window.alert(err); }
});
The request obtains success, but reply
is null and I get from web console:
XML Parsing Error: not well-formed
Location: http://localhost:8585/web/test
Line Number 1, Column 1: {"name": "jsontest","type":"jsonobject"}
I tried to specify mimeType: "application\json"
but I got the same behavior. Instead, when I don't specify dataType
or I put contentType: "json"
I succeed to read correctly the JSON string but still I get the XML Parsing Error
.
Can anyone explain why I get a XML Parsing Error while I am supposing to exchange JSON?
NOTE: I'm using Firefox and Tomcat9.
Thank you in advance.
Upvotes: 2
Views: 3220
Reputation: 73
Simply, I found out that while I was expecting json content in the request through dataType
, the servlet was not specifying that its response was coded with that type too.
Adding:
response.setContentType("application/json");
solved the problem.
Upvotes: 2