jQuery成功函数不从servlet响应返回消息

时间:2015-10-09 14:42:44

标签: java jquery

我正在使用创建一个登录页面,servlet但我似乎无法读取返回的响应,当响应为true时,它必须转到success.jsp页面但它不,我不知道我做错了什么,请帮忙。 我在这里:

JS

$.ajax({
      url: "LoginServlet",
      type: "post",
      data: {
        "username": username,
        "password": password
      },
      cache: false,
      success: function(data) {
        var xhr = data.msg;
        if (xhr === "true") {
          alert(xhr);
          window.location.href = "success.jsp";

        } else {
          alert(xhr);
        }
      }

我的servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
      LoginDAO dao = new LoginDAO();
      String username=request.getParameter("username");
      String password=request.getParameter("passsword");
      String msg = "false";




       Login login = dao.validateUser(username, password);

             String username1 = login.getUsername();
             String password1 = login.getPassword();
       if(LoginDAO.isEqual(username, password1) && LoginDAO.isEqual(password, password1)){

                msg = "true";

       }


       response.setContentType("text/plain");
       response.getWriter().write(msg);


   }

2 个答案:

答案 0 :(得分:1)

我直接指定了用户名&密码,但你应该从UI获取它们。 修改您的客户端代码,如下所示:

<script>
  $(document).ready(function() {
    $("button").click(function() {
      var username = "admin";
      var password = "admin";
      $.ajax({
        url: "LoginServlet",
        type: "post",
        data: {
          "username": username,
          "password": password
        },
        cache: false,
        success: function(data) {
          console.log("data: " + data);
          var xhr = data;
          console.log("xhr: " + xhr);
          if (data == "true") {
            alert(xhr);
            window.location.href = "success.jsp";

          } else {
            alert(xhr);
          }
        }
      });
    });

  });
</script>

你输入密码密码错误,请更正

String username = request.getParameter("username");
String password = request.getParameter("password");

答案 1 :(得分:0)

在您的代码中,此代码:

response.setContentType("text/plain");
response.getWriter().write(msg);

使用值text/plaintrue设置回复类型false

然后,在jQuery.ajax()函数中将var xhr = data.msg;更改为var xhr = data;

$.ajax({
    url: "LoginServlet",
    type: "post",
    data: {
        "username": username,
        "password": password
    },
    dataType: "text", // To match with the actual response type: «text/plain».
    cache: false,
    success: function (data) {
        var xhr = data; // Because «data» contains true or false.
        if (xhr === "true") {
            alert(xhr);
            window.location.href = "success.jsp";

        } else {
            alert(xhr);
        }
    }
});