我有一个结账页面,其中有一些 ajax 调用,例如,当用户更改送货国家/地区时,这些调用会更新隐藏字段。
大多数时候,这工作得很好,页面有时间在用户单击提交之前更新隐藏字段。但有时,由于连接速度慢或其他原因,ajax 无法及时返回隐藏字段,并且允许用户提交不完整的表单。
阅读此处的另一个问题后,我使用 ajaxStart 和 ajaxComplete 禁用并重新启用表单的提交按钮。
我还想在按钮旁边显示“请稍候”消息,以便让用户了解正在发生的情况。
这一切都工作正常,但在 99% 的情况下,此消息会快速闪烁并消失,速度太快,无法阅读,而且看起来很分散注意力/有问题。
我想做的只是在 ajax 调用需要很长时间才能响应(表明我们的连接速度很慢)时才显示此消息 - 比如 250 毫秒?
我以前没有在 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();
});
我知道这是一个非常基本的问题,我可以轻松地用 PHP 完成它,但我是 jquery 的新手,所以我需要一些初学者的帮助!
Thanks!
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);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)