如何在经过一定时间后才显示消息jquery - 阻止表单提交

Ash*_*ley 3 ajax jquery timer

我有一个结账页面,其中有一些ajax调用,用于在用户更改交付国家时更新隐藏字段.

大多数情况下,这很好用,页面有时间在用户单击提交之前更新隐藏字段.有些时候,由于连接速度慢或者ajax没有及时返回隐藏字段而且允许用户提交不完整的表单.

在这里阅读了另一个问题后,我使用ajaxStart和ajaxComplete来禁用并重新启用表单的提交按钮.

我还想在按钮旁边显示"请稍候"消息,以便让用户了解正在发生的事情.

这一切都很好,但在99%的情况下,这个消息闪烁并快速消失,读取太快,看起来分散注意力/错误.

我想做的只是显示此消息,如果ajax调用需要很长时间才能响应(表明我们的连接速度很慢) - 比如250ms?

我之前没有在jquery中使用计时器,所以这有望帮助我掌握所涉及的概念.

这是迄今为止的功能

// if we're waiting for any ajax to complete we need to disable the submit
$(document).ajaxStart(function() {
  $(".ajaxbutton").attr("disabled", "disabled");
  // if it's taken longer than 250ms (say) display waiting message
      $('#processingAlert').html(' ...please wait one moment');
      $('#processingAlert').show();
      // end the if here
})
$(document).ajaxComplete(function() {
  $(".ajaxbutton").removeAttr("disabled");
    $('#processingAlert').hide();
});
Run Code Online (Sandbox Code Playgroud)

我知道这是一个非常基本的问题,我可以很容易地做到这一点在PHP,但我是一个新手,jQuery的,所以我还需要一点初学者的帮助!

谢谢!

小智 8

setTimeout是你的朋友.

下面的内容应该有效,虽然我没有测试它是否有错别字等.

// if we're waiting for any ajax to complete we need to disable the submit
$(document).ajaxStart(function() {
  $(".ajaxbutton").attr("disabled", "disabled");
  // if it's taken longer than 250ms (say) display waiting message
  timer = setTimeout(function() {
    $('#processingAlert').html(' ...please wait one moment');
    $('#processingAlert').show();
  }, 250);
})
$(document).ajaxComplete(function() {
  $(".ajaxbutton").removeAttr("disabled");
    $('#processingAlert').hide();
    // cancel showing the message when the ajax call completes.
    clearTimeout(timer);
});
Run Code Online (Sandbox Code Playgroud)