JQuery从内部提交函数提交表单 [英] JQuery Submit Form From Inside Submit Function

查看:64
本文介绍了JQuery从内部提交函数提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我想在JQuery脚本中执行的操作。在下面的提交函数(第4节)中,我想确定表单是否有文件输入并使用ajax或只提交没有ajax的常规表单提交。换句话说,如果表单已上传,请定期提交。

The following is what I'd like to do in my JQuery script. In the submit function (4th) below, I want to decide if the form has file input and submit with either ajax or just a regular form submit without ajax. In other words, if the form has upload, do a regular submit.

我在下面的提交功能中写了这个问题。这是我唯一能让它发挥作用的东西。

I wrote the question in the submit function below. That is the only thing I need to make it work.

谢谢!

function FindFileInput(){
   // check for file input
   var FileInput = $('input:file');
   if(FileInput.length > 0){
      return true;
   }else{
      return false;
   }
}

function validation(){
  // code to validate form
  ...
}

function ajaxSubmit(formData){
   $.ajax({
      // ajax submit code
   });
}

$(myForm).submit(function(e){
   e.preventDefault();

   // 1. if NO file input present
   if(FindFileInput() === false){
      if(validation() === true){
         // serialize and call ajaxSubmit function
      }
   }

   // 2. if file input IS present
   if(FindFileInput() === true){
      if(validation() === true){
         // QUESTION: How do I submit the form here???
      }
   }
});


推荐答案

来自 http://api.jquery.com/submit/


现在提交表单时,会提示消息。这在实际提交之前发生
,因此我们可以通过
取消提交操作,在事件对象上调用.preventDefault()或从我们的处理程序返回false
。当我点击另一个
元素时,我们可以手动触发事件:

Now when the form is submitted, the message is alerted. This happens prior to the actual submission, so we can cancel the submit action by calling .preventDefault() on the event object or by returning false from our handler. We can trigger the event manually when another element is clicked:

所以请改变你的逻辑。不要将e.preventDefault()作为默认值调用,然后尝试撤消它,而只是在实际需要时调用它。

So turn your logic around. Don't call e.preventDefault() as default and then try to undo it, but rather only call it when it is actually needed.

$(myForm).submit(function(e){

    // 1. if NO file input present
    if(FindFileInput() === false){
        if(validation() === true){
            ajaxSubmit(formdata);
        }
     }

     // 2. if file input IS present
     if(FindFileInput() === true){
         if(validation() === true){
             return true; // submit form as normal, don't call e.preventDefault()
         }
     }

     // Prevent form from submitting normally
     e.preventDefault();
     return false;
});

这篇关于JQuery从内部提交函数提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆