【Ajax】解决Ajax成功处理后只响应error,不进入success的问题

一、问题描述

前端请求代码

$.ajax({

url: 'getOne',

data: {

name: 'zhangsan',

pwd: '123'

},

type: 'get',

dataType: 'json',

success: function (res) {

alert("成功" + res)

},

error: function (xhr, errorMessage, e) {

alert("失败" + errorMessage);

}

})

后端servlet代码

@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 {

// 设置编码

response.setContentType("application/json;charset=utf-8");

// 处理业务逻辑

// 响应请求,使用流的方式肯能会有IO异常,所以捕捉异常

PrintWriter out = response.getWriter();

try {

out.write("ajax请求成功");

out.close

} catch (Exception exception) {

out.write(exception);

}

out.close();

}

}

然后就发现每次处理完以后就会只响应异常error函数,进不去success

二、问题解决

上边的代码乍一看没什么问题。起初我也这么以为。但经过一番分析以后发现是因为后端的返回值类型格式不正确造成的

什么意思呢?

我在后端响应设置了json格式

response.setContentType("application/json;charset=utf-8");

但是我在响应时用流输出的是普通字符串,并不是json格式字符串

out.write("ajax请求成功");

怎么解决呢?

方法一:将字符串格式改为json格式 后端输出:out.write("{‘data’:'ajax请求成功'}"); 前端:alert("成功" + res.data)

方法二:将请求和处理的类型改为text 后端:response.setContentType("application/json;charset=utf-8"); 前端:dataType: 'text'