Today when using the Jquery.ajax method to invoke the background method, the AJAX parameter data type is "JSON", the background debug debugging, run normally, return to the normal result set, but the front end has always been into the Ajax error method, baffled its solution, after a probe to what, After adding data to the parameters of the error method, we found that readystate = 4 and status=200 in data, which also proves that there is no problem with Ajax access and that there are no exceptions. Back to find that I returned in the background is a string, but not the standard JSON format string, so the front-end JS can not enter the success. Unable to parse data in JSON format, error error. You can turn the result set into a JSON-formatted string by the background. or change the data type to "text"
Instance:
Js:
$.ajax ({
URL: ".. /.. /helloworld ",
Type: "POST",
Data: {ID: ' 12222 '},
DataType: ' Text ',
Async:false,
Success:function (data,textstatus) {
Console.log (Textstatus);
Alert ("Success");
},
Error:function (errormsg) {
Console.log (ERRORMSG);
}
});
Servlet:
Note Before class: @WebServlet ("/helloworld")
public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
Response.setcontenttype ("text/html");
Request.setcharacterencoding ("Utf-8");//This is transcoding
String id=request.getparameter ("id");
PrintWriter out = Response.getwriter ();
Out.write ("Success21");
Out.flush ();
Out.close ();
}
Xml:
<servlet>
<servlet-name>HelloWorld</servlet-name> class Name
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
S