Pol*_*hic 4 javascript ajax jquery timeout
我有一个 jQuery 代码,它只是发出一些 ajax 请求。
大多数情况下,获得响应的时间不到一秒钟,因此我可以向用户显示结果。
但有时(大约 5% 的重新加载)需要几秒钟(我可以接受,服务器有点忙)。
当需要超过 2 秒时,我想显示“请稍候”文本。但是当它需要不到 2 秒时就不会(这样用户就不会被快速显示/隐藏消息弄糊涂了)。
如何以最高效、最简单的方式实现?
当前的 jQuery 代码:
jQuery.ajax({
url: "loadData.php",
dataType: 'json',
type: 'GET',
success: function(result){
showResultsToUser(result);
}
});
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
var cancelMe = setTimeout(function() {
$('#loading').show(); // assuming your loading element has the id "loading"
}, 2000); // show loading element in 2 seconds
jQuery.ajax({
url: "loadData.php",
dataType: 'json',
type: 'GET',
success: function(result){
showResultsToUser(result);
clearTimeout(cancelMe); // don't run if it hasn't run yet
$('#loading').hide(); // hide the loading element if it's shown
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
742 次 |
| 最近记录: |