问题描述
以下是我想在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???
}
}
});
推荐答案
来自:
所以请改变你的逻辑。不要将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从内部提交函数提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!