如何让表单在提交之前等待ajax完成

How to make a form wait for ajax to finish before it submits?

本文关键字:等待 ajax 完成 提交 表单      更新时间:2023-09-26

因此,只有当使用ajax从数据库验证条件时,我才想提交一个表单。如果条件为true,即如果用户不是居民,则我使用preventDefault()方法,在ajax successs function中将变量设置为true,然后调用preventDefault(),但是,在执行此操作时,表单总是提交。即使async设置为false,它也不会等待ajax完成。这是代码。

  $('#button').click(function(e) {    
    if ($('#ca_resident').prop('checked') == true) { 
      amount=$('#user-amount').val().replace(/[,]/g,"");
      project_name=$('#project_name').val();
      var not_resident = false;
       $.ajax({
        url: '/main/verify_residence/',
        type: 'POST',
        aysnc: false,
        data: {
          value: amount,
          name: project_name
        },
        success: function(data){
          $("#verify_residence").html(data);
          not_resident = true;
        },
        dataType: 'html'
      }); 
    }
    if(not_resident){
      e.preventDefault();
    }
  });

这是行不通的。成功将在:之后发射

if(not_resident){
      e.preventDefault();
    }

因为它是异步的。您需要始终取消点击按钮,然后在点击成功后提交表格:

$('#button').click(function(e) {    
   var $form = $(this).closest('form');   
   if ($('#ca_resident').prop('checked') == true) { 
      amount=$('#user-amount').val().replace(/[,]/g,"");
      project_name=$('#project_name').val();
       $.ajax({
        url: '/main/verify_residence/',
        type: 'POST',
        aysnc: false,
        data: {
          value: amount,
          name: project_name
        },
        success: function(data){
          $("#verify_residence").html(data);
          $form.submit();
        },
        dataType: 'html'
      }); 
    }

    e.preventDefault();
  });