twitter-bootstrap 如何在 Bootstrap 中使用 AJAX 发送表单数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28689437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 22:22:07  来源:igfitidea点击:

how to send form data using AJAX in Bootstrap?

jqueryajaxtwitter-bootstrapjspservlets

提问by Lemon Juice

I have a web application which is designed by twitter bootstrap. There is a JSP page with a small form, and I need to send its data to a Servletwithout reloading the page. Below is my form.

我有一个由twitter bootstrap. 有一个带有小表单的 JSP 页面,我需要将其数据发送到 aServlet而不重新加载页面。下面是我的表格。

<!--add custom item -->

<div class="modal fade" id="customItemModel" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header"> <a href="#" data-dismiss="modal"> <img src="images/arrow-back-512.png"  width="30px" height="30px"> <small>Back</small></a> <span id="myModalLabel" style="margin-left:20px;"><font size="+2"><b>Add Custom Item</b></font></span> </div>
      <div class="modal-body">
          <form class="form-horizontal" method="get" action="PastSurgicalCustomItem" id="customItemForm"  onsubmit="formSubmit(); return false;">
        <fieldset id="modal_form">

          <!-- Text input-->
          <div class="form-group">
            <label class="col-md-1 control-label" for="textinput">Name</label>
            <div class="col-md-8">
              <input name="customName" type="text" placeholder="" class="form-control input-md">
            </div>
          </div>


          <div class="modal-footer">
              <button id="additional" class="btn btn-primary" data-dismiss="modal">Submit</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          </div>
        </fieldset>
      </form>
    </div>
  </div>
</div>

<!-- /add custom item -->  

I use the below ajax query to send data to the servlet. This code is in the same page where the above form also in.

我使用下面的 ajax 查询将数据发送到 servlet。此代码位于上述表单所在的同一页面中。

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

  function formSubmit(){

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



            //alert($textbox.attr("id"));
    }
});
}
</script>

We have loaded the below scripts to the JSP page as well.

我们也将以下脚本加载到 JSP 页面。

!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- Custom CSS -->
<link href="css/simple-sidebar.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>

    <![endif]-->
<!-- jQuery -->

<script src="js/jquery.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="js/bootstrap.min.js"></script>

Below is my servlet.

下面是我的 servlet。

import DB.PastSurgicalHistoryTypeTable;
import beans.main.PastSergicalHistoryTypeBean;
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;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Yohan
 */
public class PastSurgicalCustomItem 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/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8");

        String name = request.getParameter("customName");
        System.out.println(name);

    }


    @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";
    }

}

The problem I am having is that the ajax is not sending data to the servlet. I used the same code without bootstrap as well, so I am thinking whether bootstrap has to do something with this. How can I solve this problem?

我遇到的问题是 ajax 没有向 servlet 发送数据。我也使用了没有引导程序的相同代码,所以我在考虑引导程序是否必须对此做些什么。我怎么解决这个问题?

回答by Lemon Juice

I managed to solve the issue. The way it works with bootstrap is different. Below is my new code.

我设法解决了这个问题。它与引导程序一起工作的方式是不同的。下面是我的新代码。

<script>
 $(function() {
//twitter bootstrap script
 $("button#submit").click(function(){
         $.ajax({
     type: "POST",
 url: "PastSurgicalCustomItem",
 data: $('form.form-horizontal').serialize(),
         success: function(msg){
                  alert(msg);
         },
 error: function(){
 alert("failure");
 }
       });
 });
});
</script>

You can get more idea from here - http://www.krizna.com/jquery/jquery-ajax-form-submit-using-twitter-bootstrap-modal/

您可以从这里获得更多想法 - http://www.krizna.com/jquery/jquery-ajax-form-submit-using-twitter-bootstrap-modal/