繁体   English   中英

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

[英]Sending AJAX request before submitting the form

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

方法:1.我解决了问题

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

但是我认为这不是最优雅的解决方案。 您能解释一下为什么只有在我放置document.myform.submit(); in success它才起作用吗document.myform.submit(); in success 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>

如@harsh所指出的,在get请求收到有效响应后,调用成功函数。 因此,它将在获取请求之后发生。 我相信,即使我尚未测试,也可以按照您的要求进行以下操作:

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM