如何在 AJAX 事件完成之前暂停提交事件

How to pause a submit event until an AJAX event finishes?

本文关键字:事件 暂停 提交 AJAX      更新时间:2023-09-26

我有一个表格和一个提交。如果某些内容已填充,在提交之前,我想确保它具有良好的价值(使用 ajax),如果是这样,那么我只能让它继续。所以

$('#contact').submit(function() {
  // ajax
  $.ajax({
    type: 'POST',
    url: $(this).attr('ajaxgetaccommodationsbyemail'),
    success: function(answer) {
        here a popup window opens, which waits  until I press YES or NO
    },
    async: false
  });
   this is when return TRUE or FALSE
   there should be something like
   do while (popupWindowClosed)
   so $.when is not an option
});

你可以用jQuery阻止提交,然后实际调用本机提交来发送表单

$('#contact').on('submit', function(e) {
    e.preventDefault();
    var form = this;
    $.ajax({
        type: 'POST',
        url: $(this).attr('ajaxgetaccommodationsbyemail'),
        success: function(answer) {
             popup(function(yesorno) {
                 if (yesorno) {
                     form.submit();
                 }
             });
        }
    });
});

并且删除了async:false,因为您永远不应该执行同步 ajax。

jQuery ajax 有错误和成功回调。您可以执行以下操作:

$('#contact').submit(function() {
  // ajax
  $.ajax({
    type: 'POST',
    url: $(this).attr('ajaxgetaccommodationsbyemail'),
    error: function (request, error) {
        // there was error. handle it how you want
    },
    success: function () {
        // open your pop up window 
        // and do other stuff
    }
  });
});
$('#contact').submit(function(e) {
  e.preventDefault();
  var form = $(this);
  // ajax
  $.ajax({
    type: 'POST',
    url: $(this).attr('ajaxgetaccommodationsbyemail'),
    success: function(answer) {
        $.dialog(function(){ // this line is "pseudocode", put the code of your dialog here.
          // when clicked YES
          form.submit();
        }, function(){
          // when clicked NO
        });
    }
  });
});

如果您确实想要一个可自定义的对话框,您可以使用: https://jqueryui.com/dialog/#modal-confirmation