我有一个表单,一旦有人单击"提交",就会触发Ajax,并使用e.preventDefault();
,这样表单就不会真正提交。
我的问题是:我确实希望表单提交到服务器,但只有在Ajax成功返回之后。
因此,作为一个例子,我试图实现以下场景:
- 用户单击"提交"
- Ajax发送一些信息时被触发,用户仍留在页面上
- Ajax已经恢复了,我们现在可以启动它的
success:
函数 - 启动成功功能,并将站点上的
form data
提交给服务器
html:
<form name="demoFiler" action="save/uploadCreate.php" method="POST" enctype="multipart/form-data">
//Some inputs, checkboxes radios etc.
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload hideButton" />
</form>
Javascript:
document.getElementById(this.config.form).addEventListener("submit", submitMe, false);
function submitMe(e){
e.stopPropagation(); e.preventDefault();
//Necessary vars for the 'data' defined here
$.ajax({
type:"POST",
url:this.config.uploadUrl,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse){
//This is where we need our Success function to SUBMIT the form using uploadCreate.php
}
});
}
将按钮绑定到单击事件而不是表单提交事件,然后在success
ajax回调中对表单元素启动.submit
函数。
$("#submitHandler").click(function(e) {
e.preventDefault();
//Fill "data" variable
var data = {};
//set the url
var url = "someurl";
$.ajax({
type:"POST",
url:url,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse){
//test rponse then do below.
$("form[name=demoFiler]").submit();
}
});
});
由于您已经在使用jQuery,请尝试以下操作:
$('#'+this.config.form).submit(function(e) {
var $this = $(this);
e.stopPropagation();
e.preventDefault();
//Necessary vars for the 'data' defined here
$.ajax({
type:"POST",
url:this.config.uploadUrl,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse) {
// do something with rponse
$this.off('submit').submit(); // unbind the handler and submit
}
});
}