2014-09-05 91 views
1

使用函數在單獨的iframe中提交2個表單,然後在父頁面上提交表單。 (奇怪的問題是)我的方法似乎在其他計算機上工作正常,它只提交父頁上的表單。瀏覽器是相同的(firefox,相同版本)。 我不知道爲什麼會發生這種情況,以及如何解決這個問題。下面是HTML和功能表單在某些計算機上失敗的iframe中提交

<form id="projects" method="post"> 
    ... 
    <input type="submit" class="button-primary" value="" > 
    </form> 
    <iframe id="lean">...<form method="post"><input type="submit" class="button-primary" value="submit" ></form></iframe> 
    <iframe id="lean2">...<form method="post"><input type="submit" class="button-primary" value="submit" ></form></iframe> 
    <button if="herewego">Submit all</button> 

JS

$(window).load(function(){ 
$('#herewego').click(function(){ 
if ($("#lean").contents().find("#_dtm_first_name").val().length >= 1){ 
$("#lean").contents().find('.button-primary').click();} 
if ($("#lean2").contents().find("#_dtm_first_name").val().length >= 1){ 
$("#lean2").contents().find('.button-primary').click();} 
$('#projects').find('.button-primary').click(); 
}); 

在父頁面的形式重定向。 我的理論是,在超載的橋上,有足夠的時間來提交iframe內的表單,並且在較少加載的瀏覽器上它發生得太快,只有父表單被提交。是這樣,如果是這樣的話,我應該如何重構我的js,這樣兩個iframe表單在父頁面表單之前提交?

回答

1

JavaScript是異步的,所以如果你想先提交iframe表單,你需要依賴回調函數。有趣的是,JQuery的click()函數似乎沒有回調機制,因此您需要找到其他「標誌」作爲參考,例如,如何使用iframe表單提交事件?你可以確保父窗體只在另外兩個onSubmit()函數被調用後才能被提交(你可以使用計數器或其他東西)。

解決這個問題的另一種可能是過度設計的方法是使用JQuery的$.when,我之前用它來保證涉及Ajax調用的同步事件,而不是100%確定這是否適用於您的情況。這是一個很酷的技術:)

var deferreds = getSomeDeferredStuff(); 

     $.when.apply($,deferreds).done(
      function() { 
       //Only execute this block after the iframe forms are submitted 
       console.log('Success!'); 

       submitParentForm(); 

      }).fail(function() { 
       // Oh noes, something went wrong :(
       console.log('The process failed');   
      } 
     ); 

function getSomeDeferredStuff() { 
    var deferreds = []; 

    deferreds.push(submitIframeForm1()); 
    deferreds.push(submitIframeForm2()); 

    return deferreds; 
}