我有一个HTML多部分表单,包括姓名,电子邮件和文件上传。
我想先用Ajax注册用户。如果注册成功,我想继续提交表格。如果失败,我想避免提交表格。
这是我的代码:
--- HTML ---
<form id="account-form" method="post" enctype="multipart/form-data" data-ajax="false" action="upload.php" >
<input type="text" name="username" id="username" />
<input type="email" name="email" id="email" />
<input type="file" id="mediaupload" name="mediaupload" accept="image/*" />
</form>
--- JavaScript ---
accountform.submit(function(event) {
var registration_ok = true;
// See if we can register the user
// And if we can, submit the form.
$.ajax({
type: "POST",
url: "/usercreate.php",
data: postdata,
dataType: 'json',
success: function(data) {
// fine to submit the form.
},
error: function (data){
// If this fails, we don't want to submit the form!
registration_ok = false;
}
});
return registration_ok;
});
然而,它总是返回true - 我想这是因为main函数在调用Ajax错误之前返回。
如何在注册失败时阻止它返回true并提交表单?
谢谢!
答案 0 :(得分:2)
您需要始终返回false,而不是registation_ok
,然后在成功函数中,转到:
document.forms["account-form"].submit(); //edited
即。当您按下提交按钮时,永远不会提交表单,等待AJAX返回,然后只有在注册成功时才提交表单。
答案 1 :(得分:0)
为什么不在.ajax语句中的onSuccess处理程序中以编程方式提交表单?
这样的事情:
document.forms["account-form"].submit();
答案 2 :(得分:0)
你可以进行syncronic ajax调用,只需添加async:false,参数
答案 3 :(得分:0)
抱歉,我误解了这个问题。在success方法内部触发form.submit();
答案 4 :(得分:0)
问题是AJAX调用是异步的,因此在函数返回success
值之后才会调用error
和registration_ok
函数。设置为true
)。