gpt4 book ai didi

JavaScript:表单提交前 Ajax 调用的控制逻辑?

转载 作者:行者123 更新时间:2023-12-02 20:15:00 24 4
gpt4 key购买 nike

我有一个 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并提交表单?

谢谢!

最佳答案

您需要始终返回 false,而不是 registation_ok,然后在 success 函数中执行:

document.forms["account-form"].submit(); //edited

即按下提交按钮时不要提交表单,等待 AJAX 返回,只有注册成功后才提交表单。

关于JavaScript:表单提交前 Ajax 调用的控制逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6429682/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com