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

JavaScript: control logic for Ajax call before form submit?

本文关键字:控制 调用 Ajax 表单提交 JavaScript      更新时间:2023-09-26

我有一个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——我想这是因为主函数在调用Ajax错误之前返回

当注册失败时,我如何防止它返回true并提交表格?

谢谢!

您需要始终返回false,而不是registation_ok,然后在成功函数中,转到:

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

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

为什么不在.ajax语句中的onSuccess处理程序中以编程方式提交表单?

类似这样的东西:

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

您可以进行syncronic ajax调用,只需添加async:false,参数

对不起,我误解了这个问题。在成功方法内部触发form.submit();

问题是AJAX调用是异步的,所以successerror函数只有在函数返回registration_ok值(您将其预设为true)之后才会被调用。