如何使用JQuery正确提交表单?

时间:2015-05-22 09:37:32

标签: java jquery twitter-bootstrap jsp servlets

我正在尝试检查表单中给出的用户名是否已在数据库中可用,否则将表单数据提交到数据库。

我正在使用JSP和Servlet。

下面是我的JSP代码。

 <script>
$('#theForm').submit(function() { // catch the form's submit event
    $.ajax({ // create an AJAX call...
        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
            alert(response); // update the DIV
        }
    });
    return false; // cancel original event to prevent form submitting
});
</script>      

 <form id="theForm" class="form-horizontal form-login" action="CheckExistingUser" method="post" data-parsley-validate>
<fieldset>

<!-- Form Name -->
<legend class="legend">Apply For The Account</legend>

<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">Company Name</label>  
  <div class="col-md-6">


<!-- Text input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="textinput">User Name</label>  
  <div class="col-md-6">  

 <table>
    <tr>      
      <td style="width: 125%"> <input id="textinput" name="userTxt" type="text" placeholder="" class="form-control input-md" required></td>
      <td id="phoneTxtError" class="red">&nbsp;</td>
    </tr>

 </table>   

  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Password</label>
  <div class="col-md-6">

  <table>
    <tr>      
      <td style="width: 125%"> <input id="password" name="passwordTxt" type="password" placeholder="" class="form-control input-md" data-parsley-equalto="#password" required></td>
      <td id="passwordError" class="red">&nbsp;</td>
    </tr>

 </table>   

  </div>
</div>

<!-- Password input-->
<div class="form-group">
  <label class="col-md-4 control-label" for="passwordinput">Confirm Password</label>
  <div class="col-md-6">

 <table>
    <tr>      
        <td style="width: 125%"> <input  id="password1" name="confirmPasswordTxt" type="password" placeholder="" class="form-control input-md" data-parsley-equalto="#password" required></td>
      <td id="xpwVerifiedError" class="red">&nbsp;</td>
    </tr>    
 </table>   
    <label id="pwVerifiedError" class="red">&nbsp;</label>  
  </div>
</div>

<!-- Button -->
<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton"></label>
  <div class="col-md-4">
      <button id="singlebutton" name="singlebutton" class="btn btn-primary">Submit</button>
  </div>
</div>

</fieldset>
</form>

以下是Servlet中的代码

public class CheckExistingUser extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            String userTxt=request.getParameter("userTxt");
            List<String> list=new ArrayList<String>();  

            SubUserTable table = new SubUserTable();
            boolean isUserNameExists = table.isUserNameExists(userTxt.toLowerCase());

            if(isUserNameExists)
            {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");

                response.getWriter().write("true");
            }

        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

但是,会发生错误消息“true”打印在白色空白页而不是警告对话框中。我在这做错了什么?我也在这里使用Bootstrap。

2 个答案:

答案 0 :(得分:0)

success是一个被称为的函数,如果AJAX请求成功,它与此请求的返回结果无关,所以它获取true写在页面上是正常的。

答案 1 :(得分:0)

表单中提交的事件未注册。简单来说,您试图在页面呈现表单之前注册表单的提交事件。下面是修改后的代码。

<script>
    $(document).ready(function() {
        $('#theForm').submit(function() { // catch the form's submit event
            $.ajax({ // create an AJAX call...
                data: $(this).serialize(), // get the form data
                type: $(this).attr('method'), // GET or POST
                url: $(this).attr('action'), // the file to call
                success: function(response) { // on success..
                    alert(response); // update the DIV
                }
            });
            return false; // cancel original event to prevent form submitting
        });
    });
</script>