簡體   English   中英

JavaScript / jQuery Pause函數,然后再次將其觸發

[英]JavaScript/jQuery Pause function and then fire it again

我有一個表單,一旦有人單擊“提交”,就會觸發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
        }
    });

    }

將按鈕綁定到click事件而不是表單提交事件,然后在success ajax回調中的form元素上觸發.submit函數。

$("#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();
    }
   });
});

由於您已經在使用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
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM