Ajaxreadystate=4 and status=200, also enter the error method

Source: Internet
Author: User
Tags json

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.