【问题标题】:Unable to send form data to servlet using Ajax/JQuery without refreshing the page无法在不刷新页面的情况下使用 Ajax/JQuery 将表单数据发送到 servlet
【发布时间】:2015-04-24 23:18:41
【问题描述】:

我正在尝试使用 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 页面。我在这里做错了什么?

【问题讨论】:

    标签: jquery html ajax jsp servlets


    【解决方案1】:

    据我所知,您只是不阻止在表单中推送提交按钮的默认操作。此外,如果用户在字段中使用 Enter 按钮发送表单,而不是用鼠标按下按钮,您的代码也将不起作用

    尝试使用下一个构造

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

    【讨论】:

      猜你喜欢
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2020-03-18
      相关资源
      最近更新 更多