在提交表单之前发送AJAX请求

在提交表单之前发送AJAX请求

问题描述:

问题:我正在尝试发送ajax请求,然后提交表单。在提交表单之前发送AJAX请求

Aproaches: 1.我通过把

success: function() { 
    document.myform.submit(); 
} 

解决了这个问题但我认为这不是最完美的解决方案。你能解释一下为什么只有当我把document.myform.submit(); in success?有没有其他办法可以解决这个问题?

<div class="buttons"> 
    <div class="right"> 
     <form name="myform" onsubmit="javascript: startAjax(); return false;" action="https://example.com/payment.php" method="get"> 
        <input type="hidden" name="merchantId" value="<?php echo $merchantIdKZM; ?>"> 
        <input type="submit" value="<?php echo $button_confirm; ?>" id="button-confirm2" class="button" name="PayKZM" /> 
       </form> 
    </div> 
</div> 

<script type="text/javascript"> 
function startAjax() { 
    console.log("dafaaaa"); 
    $.ajax({ 
       type: 'get', 
       url: 'index.php?route=payment/bank_transfer/confirm', 
       async: 'false', 
       success: function() { 

         // location = '<?php echo $continue; ?>'; 
       }    
     }); 

} // Calls ajaxComplete() when finished 

function ajaxComplete() 
{ 
    console.log("dafa"); 
    document.myform.submit(); 
} 
</script> 
+0

堂妹'当您收到从我不在服务器 – shashwat 2013-04-21 07:50:12

+1

您请求的有效响应success'函数被调用看看为什么在成功功能中使用该代码不是一个好的解决方案。你是否总是提交表单,或者你是否试图从AJAX的响应中检查某些内容? – user1048676 2013-04-21 07:51:25

+0

我总是提交表单。 – max 2013-04-21 17:19:07

成功的函数在获取请求接收到@harsh指出的有效响应时被调用。因此它会在获取请求之后发生。我相信,虽然我没有测试它作为您的要求类似于下面的东西会做:

<script type="text/javascript"> 
$(function() { 
    $("#form").on('submit', function() { 
     var $form = $(this); 
     $.ajax({ 
      type: 'GET', 
      url: 'index.php?route=payment/bank_transfer/confirm', 
      data: $form.serialize(), 
      async: 'false', 
      success: function() { 
       $.ajax({ 
        type: 'GET', 
        url: 'https://example.com/payment.php', 
        data: $form.serialize(), 
       }); 
      } 

     }); 
    }); 
}); 
</script>