在onsubmit函数完成之前提交表单

时间:2012-03-26 21:08:10

标签: javascript jquery

我在提交表单时调用了JavaScript函数,但是在完成提交函数之前表单已经提交。如果我在onsubmit函数中使用alert它首先完成函数然后提交表单。我使用settimeout函数代替警报但它没有用。如何在提交完成后提交表格。

function chat1close(name){
    var abc;
    abc=window.frames[0].test();
    $.ajax({
        type:'GET',
        url:'modules/closechat.php?abc='+abc+'&name='+name,
        success:function(data){

        }
    });
    document.getElementById("hello").innerHTML=" ";
    alert("yes");
    return true;
}

4 个答案:

答案 0 :(得分:1)

async: false添加到您的ajax调用中。这将阻止它在函数返回之前执行函数的其余部分。

答案 1 :(得分:1)

如果chat1close是表单上正在执行的函数,并且您希望代码执行synchronously,请在.ajax请求中设置以下选项:

async:false,

http://api.jquery.com/jQuery.ajax/

答案 2 :(得分:1)

在函数完成之前不会发送表单,但是您在函数中进行异步AJAX调用,并在AJAX响应到达之前发送表单并调用成功回调函数。

在发送表单之前进行AJAX调用的唯一方法是使用同步AJAX调用,但这会在等待响应时冻结浏览器:

function chat1close(name){
  var abc = window.frames[0].test();
  $.ajax({
    type: 'GET',
    async: false,
    url: 'modules/closechat.php?abc='+abc+'&name='+name,
    success:function(data){
      document.getElementById("hello").innerHTML=" ";
      alert("yes");
    }
  });
  return true;
}

但是,您可以停止发送表单,而是在AJAX响应到达后发送表单:

function chat1close(name){
  var abc = window.frames[0].test();
  $.ajax({
    type: 'GET',
    async: false,
    url: 'modules/closechat.php?abc='+abc+'&name='+name,
    success:function(data){
      document.getElementById("hello").innerHTML=" ";
      alert("yes");
      $('#IdOfTheForm')[0].submit();
    }
  });
  return false;
}

答案 3 :(得分:1)

简单的方法:

    var $form = jQuery("#the_form");
    var should_submit = false;
    $form.submit(function () {
        if (should_submit)
           return true;

        $.post('some/async/thing', function () {
        //This is an async callback that
        //will set the should submit var to true and resubmit form.
        should_submit = true;
        $form.submit();  //will now submit normally because should_submit is true.
        });
        return false;
    });
相关问题