2015-09-22 22 views
0

用戶可以添加新的表單,只需點擊一下按鈕和「jQuery表單插件」即可。要提交每個表單,我遍歷具有某個類的表單。jQuery表單插件提交了幾個表單,但等到之前結束

由於用戶可以提交圖像,並且服務器必須對每個圖像做一些工作,我希望等待上一次提交完成後才能成功statusText。目前(我只是做了超時2000年,這只不過是一個「hackish」解決方案。)

我想我可以使用成功函數,但不知道如何連接我的提交循環與返回的成功statusText。這是一個fiddle。 這裏我有什麼:

var userform = '<form class="myForm" action="up.php" method="post"> ' + 
         'Name: <input type="text" name="name" />' + 
         'file: <input type="file" name="img[]" multiple />' + 
         'Comment: <textarea name="comment"></textarea>' + 
         '<input type="submit" value="Submit Comment" />' + 
        '</form>'; 


    function showResponse(responseText, statusText, xhr, form) { 
     if (statusText === "success") { 
      console.log("the submit ended with success"); 
      //submit next form should happen 
     } 
    } 

    var options = { 
     success: showResponse 
    }; 

    $('#add').click(function() { 
     $(userform).appendTo('.append').each(function() { 
      $('.myForm').ajaxForm(options); 
     }); 
    }); 


    $("#all").click(function() { 
    var collection = $('.myForm'); 
    if (collection.length > 0) { 
     var i = 0; 
     var fn = function() { 
      var element = $(collection[i]); 
      $(element).submit().addClass('done').hide("slow"); 
      if (++i < collection.length) { 
       setTimeout(fn, 2000); 
      } 
     }; 
     fn(); 
    } 
    }); 

謝謝!

回答

0

提交處理程序只是做一個std POST/GET,所以你不會得到迴應。你會想改變你的代碼,使用AJAX,然後在服務器返回的success = true/false響應或任何你喜歡的

https://jsfiddle.net/mj9dbLh1/3/

改變了...

var element = $(collection[i]); 
$(element).submit().addClass('done').hide("slow"); 
if (++i < collection.length) { 
    setTimeout(fn, 2000); 
} 

喜歡的東西...

var element = $(collection[i]); 
$(element).addClass('done').hide("slow"); 
$.post("ajax/test.html", function(data) { 
    fn(); // DO SUCCESS ACTION HERE 
}); 

請記住,這將在每次成功時執行因此,您可能需要首先獲取表單數(wh ich給你ajax調用的次數)。然後增加每個成功操作的計數。一旦你得到你的總數,你可以顯示所有的成功。

看看這些文檔,以獲取更多關於如何處理錯誤和不是的錯誤線索。 http://api.jquery.com/jquery.post/

+0

嗨ductiletoaster,感謝您的回答,兩個問題。您的解決方案觸發了數百個請求,我怎麼能阻止這種情況,即只有一個新的請求才會成功。此外,你說我沒有得到我的提交回應,但不是這個成功的功能是什麼?它給了我成功的回報。謝謝! –

+0

無視。我看到兩個onClick事件完全分開。我的答案不再有意義。 – ductiletoaster