JavaScript / jQuery暂停功能,然后再次触发它

时间:2013-08-03 15:31:02

标签: php javascript forms

我有一个表单,一旦有人点击“提交”,就会触发Ajax并使用e.preventDefault();,以便表单实际上不会提交。

我的问题:我确实希望将表单提交给服务器,但只有在Ajax成功回来之后。

作为一个例子,我试图实现以下场景:

  • 用户点击“提交”
  • Ajax被解雇发送一些信息,用户仍然在页面上。
  • Ajax已经过去了,我们现在可以启动它的success:功能。
  • 触发成功功能,并将网站上的form data提交给服务器。

html:

   <form name="demoFiler" action="save/uploadCreate.php" method="POST" enctype="multipart/form-data">

        //Some inputs, checkboxes radios etc.

        <input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload hideButton" />

    </form>

Javascript:

    document.getElementById(this.config.form).addEventListener("submit", submitMe, false);

    function submitMe(e){
    e.stopPropagation(); e.preventDefault();

    //Necessary vars for the 'data' defined here

    $.ajax({
        type:"POST",
        url:this.config.uploadUrl,
        data:data,
        cache: false,
        contentType: false,
        processData: false,
        success:function(rponse){
                         //This is where we need our Success function to SUBMIT the form using uploadCreate.php
        }
    });

    }

2 个答案:

答案 0 :(得分:1)

将按钮绑定到单击事件而不是表单提交事件,然后在.submit ajax回调中的表单元素上触发success函数。

$("#submitHandler").click(function(e) {
   e.preventDefault();

   //Fill "data" variable
   var data = {};

   //set the url
   var url = "someurl";

   $.ajax({
    type:"POST",
    url:url,
    data:data,
    cache: false,
    contentType: false,
    processData: false,
    success:function(rponse){
       //test rponse then do below.
       $("form[name=demoFiler]").submit();
    }
   });
});

答案 1 :(得分:0)

由于您已经在使用jQuery,请尝试以下方法:

$('#'+this.config.form).submit(function(e) {
    var $this = $(this);
    e.stopPropagation(); 
    e.preventDefault();

    //Necessary vars for the 'data' defined here

    $.ajax({
        type:"POST",
        url:this.config.uploadUrl,
        data:data,
        cache: false,
        contentType: false,
        processData: false,
        success:function(rponse) {
            // do something with rponse
            $this.off('submit').submit(); // unbind the handler and submit
        }
    });
}