无法在不刷新页面的情况下使用Ajax / JQuery将表单数据发送到servlet

时间:2015-02-23 15:21:17

标签: jquery html ajax jsp servlets

我正在尝试使用Ajax / JQuery将一些数据从Form发送到Servlet而不刷新页面。下面是我的JSP页面。

<%-- 
    Document   : index
    Created on : Feb 23, 2015, 8:18:52 PM
    Author     : Yohan
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
   var form = $('#customItemForm');
  function formSubmit(){

 $.ajax({
     url:'SampleServlet',
     data: $("#customItemForm").serialize(),
     success: function (data) {

    }
});
}
</script>
    </head>
    <body>
        <form method="get" action="SampleServlet" id="customItemForm">
            Name <input type="text" name="name">
        <button onclick="formSubmit()">Submit</button>
        </form>
    </body>
</html>

下面是我的servlet。

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

/**
 *
 * @author Yohan
 */
public class SampleServlet extends HttpServlet {



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

            String str = request.getParameter("name");
            System.out.println(str);
        } finally {
            out.close();
        }
    }


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

但是我的表单总是被提交给servlet,而不是JSP页面。我在这做错了什么?

1 个答案:

答案 0 :(得分:1)

据我所见,您不会阻止在表单中按提交按钮的默认操作。如果用户使用Enter按钮进入字段发送表单,而不是按下鼠标按钮

,则代码将无法工作

尝试使用下一个构造

<form method="get" action="SampleServlet" id="customItemForm"  onsubmit="formSubmit(); return false;">
    Name <input type="text" name="name">
    <button>Submit</button>
</form>