如何在AJAX事件结束之前暂停提交事件?

时间:2016-01-28 22:13:57

标签: javascript jquery ajax

我有表格和提交。如果有东西被填满,在提交之前我想确保它的价值很高(用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

});

3 个答案:

答案 0 :(得分:6)

您可以使用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。

答案 1 :(得分:1)

$('#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

答案 2 :(得分:1)

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
    }
  });

});