[Solved] it only responds to error and does not enter success after AJAX is successfully processed

1. Problem description

Front end request code

    url: 'getOne', 	
    data: {		
        name: 'zhangsan',
        pwd: '123'
    type: 'get',		
    dataType: 'json',	
    success: function (res) { 
        alert("成功" + res)
    error: function (xhr, errorMessage, e) { 
        alert("失败" + errorMessage);

Backend servlet code

@WebServlet(name = "getOne", urlPatterns = "/getOne")
public class GetOne extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      	// Set encoding
       // Processing business logic
         // Responding to the request, there may be IO exceptions in the way of using the stream, so the exception is caught
        PrintWriter out = response.getWriter();
        try {
            out.write("ajax request successful");
        } catch (Exception exception) {

Then it is found that after each processing, it will only respond to the abnormal error function and cannot enter success

2. Problem solving

The code above looks OK at first glance. I thought so at first. However, after some analysis, it is found that the format of the return value type at the back end is incorrect

What do you mean?

I set the JSON format in the back-end response


However, I output the ordinary string with the stream when responding, not the JSON format string

out.write("ajax request successful");

How to solve it?

Method 1: change the string format to JSON format
back end output: out.Write ("{'data':'ajax request succeeded '}")
front end: alert ("success" + res.data) method 2: change the type of request and processing to text
back end: response.setcontenttype ("application/JSON; charset = UTF-8")
front end: datatype: 'text'

Read More: