2015-04-01 21 views
0

這是處理:我有一個表單,需要一段時間才能提交,因爲我在等待一些第三方Web服務。所以我試圖實現的是,點擊提交按鈕後,它被禁用,被分配一個特殊的類,如果提交表單超過5秒鐘,則顯示通知。setTimeOut AFTER jQuery表單提交

我想出了這一點:

$('#register_index_button').click(function(){ 
$(this).addClass('bt_button_loader'); 
$(this).val('Please wait'); 
$(this).attr('disabled', 'disabled'); 
$('#register_index_form').submit(); 

//it takes more than 5 seconds, display notice 
setTimeout(function() { 
    $('#notice').html('Still waiting ...'); 
}, 5000); 
}); 

一切工作正常,但超時功能。我猜是在我用jQuery提交表單之後,其他所有內容都被忽略了?

謝謝你的幫助!

+0

你有沒有嘗試''提交'之前'setTimeout'? – JNF 2015-04-01 13:22:05

+0

您必須將settimeout放置在窗體的事件onsubmit中。 – gaetanoM 2015-04-01 13:22:23

+0

你的表格如何?它有Web服務網址嗎?如果是,那麼它會嘗試重新加載另一個頁面,這將是Web服務調用的結果。 – Vikash 2015-04-01 13:23:54

回答

2

嘗試在「提交」事件的表單上附加事件處理程序。放置超時事件處理函數。

https://developer.mozilla.org/en-US/docs/Web/Events/submit

$('#register_index_form').on('submit', function(){ 
    setTimeout(function() { 
     $('#notice').html('Still waiting ...'); 
    }, 5000); 

}); 
+0

謝謝,作品像魅力! – rannt 2015-04-01 13:57:39

0

您應該在您的服務返回後提交,我確實沒有看到任何代碼可以這樣做,並且在您收到服務響應之後,請提交表單。

$('#register_index_button').click(function(){ 
$(this).addClass('bt_button_loader'); 
$(this).val('Please wait'); 
$(this).attr('disabled', 'disabled'); 


//it takes more than 5 seconds, display notice 
setTimeout(function() { 
    $('#notice').html('Still waiting ...'); 

}, 5000); 
}); 

將服務在ajax調用中進行檢索時使用完整的方法。

$('#register_index_form').submit(); 
+0

好吧,可能我需要提供額外的信息: 我使用Codeigniter來處理表單提交。我的表單只有一個字段,並且此字段的值將發佈到控制器,其中發生formValidation。表單驗證規則之一是一個回調函數,其中我執行SOAP請求並基於SOAP響應,回調函數返回true或false。此soap請求需要一段時間才能完成,同時用戶必須等待表單驗證結果,然後才能將其重定向到另一個頁面。 所以我想在幾秒鐘後給用戶一個通知。 – rannt 2015-04-01 13:43:31

0

作爲@gaemaf說明。

$('#register_index_button').click(function(){ 
    $(this).addClass('bt_button_loader'); 
    $(this).val('Please wait'); 
    $(this).attr('disabled', 'disabled'); 
    $('#register_index_form').submit(
     //Nested inside of the submit to be executed when submit 
     setTimeout(function() { 
      $('#notice').html('Still waiting ...'); 
     }, 5000); 
    ); 
}); 

另一種方法是收集表單中的所有字段並使用Ajax提交提交它們。

通過這種方式,您可以在啓動ajax時創建'Please wait',並確認表單已被接收並正在處理中。所以像....

$('#register_index_form').submit(function(){ 
    var url = "path/to/your/script.php"; 
    // the script where you handle the form input. 
    $.ajax({ 
     type: "POST", 
     url: url, 
     data: $("#register_index_form").serialize(), 
     // Gets the forms elements and submits them 
     timeout: 10000 
     // How long the Ajax will wait before considering the call to have failed 
    }) 
    .done(function(data) { 
      //Do something ...   
    }); 
    return false; // avoid to execute the actual submit of the form. 
});