我有一个表单,一旦有人点击“提交”,就会触发Ajax并使用e.preventDefault();
,以便表单实际上不会提交。
我的问题:我确实希望将表单提交给服务器,但只有在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
}
});
}
答案 0 :(得分:1)
将按钮绑定到单击事件而不是表单提交事件,然后在.submit
ajax回调中的表单元素上触发success
函数。
$("#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();
}
});
});
答案 1 :(得分:0)
由于您已经在使用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
}
});
}