2015-04-01 22 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. 
});