Ajax发布多次提交表单

时间:2017-07-12 08:54:30

标签: javascript jquery ajax

我将此代码用于Ajax发送的数据。我正在使用summernote编辑器。我的问题是,当我通过遗漏任何字段提交时,我的节目需要警告'然后当我填写所有字段并按下提交按钮时,表单会发送两次Ajax请求。每当我错过必填字段时才会发生。

  <script type="text/javascript">
    jQuery(document).ready(function (e) {
        jQuery('#btnSubmit').click(function(){ //btnSubmit is submit button id

            jQuery("#my_form").submit(function(event){
                event.preventDefault(); //prevent default action
                var post_url = jQuery(this).attr("action"); //get form action url
                var request_method = jQuery(this).attr("method"); //get form GET/POST method
                var form_data = new FormData(this); //Creates new FormData object
                jQuery.ajax({
                     url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",  

                    type: request_method,
                    data : form_data,
                    contentType: false,
                    cache: false,
                    processData:false,
                    success:function(data){  
                    alert ('Data Successfully Inserted');
                    //location.reload();
                    //top.location.href="admin.php?page=data_list";
                    },

                })

            });
        })
    }); 
    </script>

1 个答案:

答案 0 :(得分:1)

您可以从点击中提取提交。编写一个提交表单的函数,并在单击#btnSubmit时调用它。以下是帮助您的代码:

&#13;
&#13;
jQuery('#btnSubmit').on('click', function(event) {
  event.preventDefault(); //prevent default action
  submitForm();
})

function submitForm() {
  var post_url = jQuery("#my_form").attr("action"); //get form action url
  var request_method = jQuery("#my_form").attr("method"); //get form GET/POST method
  var form = $('form').get(0);
  var form_data = new FormData(form) //Creates new FormData object
  jQuery.ajax({
    url: "/demo/wp-admin/admin-ajax.php?action=theme_submit",

    type: request_method,
    data: form_data,
    contentType: false,
    cache: false,
    processData: false,
    success: function(data) {
      alert('Data Successfully Inserted');
      //location.reload();
      //top.location.href="admin.php?page=data_list";
    },

  })

}
&#13;
&#13;
&#13;