在jsp中处理Ajax成功和错误

时间:2018-02-15 05:13:48

标签: java ajax jsp

我在JSP中有Form,它有两个输入框以及像这样的提交和清除按钮

<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
 <table>
 <tr>
 <td>From Date</td><td><input type="text" name="n1" value=""/></td>
 </tr>
 <tr>
 <td>End Date</td><td><input type="text" name="n2" value=""/></td>
 </tr>
 <tr></tr>
 <tr>
 <td><input type="submit" name="validpro_insert" value="Insert"></td>
 <td><input type="reset" name="validpro_clear" value="Clear"></td>
 </tr>                     
 </table>
 </form>

因为我使用表单标记中的get方法调用servlet,用于通过JDBC API从数据库获取数据并处理响应,所以我使用了像这样的ajax

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    

         processRequest(request, response);
         System.out.println("In get");
          PrintWriter out = response.getWriter();
          String responseStr = "";
          responseStr = addUser(request); // Return either error/success
          System.out.println("Reponse:" + responseStr);  
           response.setContentType("application/json"); 
           response.setCharacterEncoding("utf-8"); 
           response.getWriter().write(responseStr);
           out.print(responseStr);

因为我必须编写一些代码来从servlet中的DB获取数据并将该响应返回给ajax,这样可以在同一个jsp上处理成功和错误

<script type="text/javascript" src="js/jq.js"></script>   
   <script type="text/javascript">

        var form = $('#loginForm');
        form.submit(function () {
        $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize(),

          error: function (theRequest,textStatus, errorThrown) {
                     // Success = false;
                      alert (theRequest.responseText);
                      alert(errorThrown);
                   alert('No graph found');//doesnt goes here
            },
        success: function (data) {

                var result=data;
                alert(result);
        }     
                });
                return false;
            });
        </script>

但问题是我没有从ajax中的servlet获取任何值来处理成功或错误

我认为由于servlet doget()方法代码我正面临这个问题..如果还有其他问题,请告诉我。应该感谢任何帮助

2 个答案:

答案 0 :(得分:1)

在我的代码中进行了这些更改,它成功运行

 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) 

                 String responseSend = "";

            String from = request.getParameter("n1");
            String to = request.getParameter("n2");    

              if ((from == null) || (from.equals(""))) {

                System.out.println("From null");
                responseSend = "error";

            } 
              else if ((to == null) || (to.equals(""))) {

                System.out.println("End null");
               responseSend  = "error";

            }
              else{            
                      //jdbc code              
            System.out.println("got it");
            int n1 = Integer.parseInt(request.getParameter("n1"));
            int n2 = Integer.parseInt(request.getParameter("n2"));
            responseSend = "code";           
              }

             out.print(responseSend);

        }          
            }

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
           System.out.println("In get");
            processRequest(request, response);
    }

因为我添加了一个新方法processrequest(),其中包含请求和响应参数,它们将文本/ HTML返回到同一jsp上的Ajax代码。首先,我对ajax代码中的成功/错误感到困惑,但现在我发现了

 error: function (theRequest,textStatus, errorThrown) {
                          alert (theRequest.responseText);
                          alert(errorThrown);
                },

  success: function (data) {

                var result=data;
                alert(result);
        }   

当在给定的URL上没有找到servlet时将调用该错误,并且当成功调用具有给定类型和servlet URL的servlet时将调用成功。

答案 1 :(得分:0)

我在这里粘贴了我的代码,效果很好

尝试更改参数

您的JSP页面

<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>

    

<form id="form">
    Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>

<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>

这是你的ajax

$(document).ready(function() {
$('#form').submit(function() {
    $.ajax({
        url : 'GetUserServlet',
        data : {
            userName : $('#userName').val()
        },
        success : function(responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    });
});

});

您的servlet文件

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String userName = request.getParameter("userName").trim();
    if(userName == null || "".equals(userName)){
        userName = "Guest";
    }

    String greetings = "Hello " + userName;

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

}