jQuery延迟将数据发布到div中

时间:2012-03-22 12:11:39

标签: javascript jquery http-post delay

我在jQuery中有这个函数,它使用POST从页面获取数据,然后将响应设置为div:

$("#go").click(function(){ 
   $.post("get.php", {p: 'abc'}, function(data){ 
   $('#result').html(data); 
   });
});

这样可行,但无论如何都要将数据延迟到#result标签大约3秒钟?

最终我希望标签说:

“正在加载。”,“正在加载...”和“正在加载...”各一秒,然后显示数据。

6 个答案:

答案 0 :(得分:7)

这是您应该使用的语法。

var delayCounter = 3;
var delayTimer = '';
delayTimer = setInterval(function(){
  if (delayCounter > 0){
    $('#result').html('Loading...');
  }else{
    $('#result').html(data);
    clearInterval(delayTimer);
  }
  delayCounter--;
},1000);

这里发生了什么?

  • 我们使用delayCounter变量来计算延迟操作的次数。它的起始值是3 - 所以我们将“延迟”3次。
  • delayTimer变量是计时器本身,它将计算每个延迟。
  • 我们使用setInterval函数,这正是我们想要做的 - 在执行代码之间设置间隔。
  • clearInterval非常自我解释 - 这会结束并清除计时器。
  • 对于每次迭代,我们减少 delayCounter变量,以便我们可以跟踪已经过了多少个间隔。
  • 我们使用毫秒来定义延迟 - 这里我使用了1000秒,即1秒(1000毫秒,1秒)。

您可能希望实现的另一个附加功能是,不是简单地在元素中放置“正在加载”文本,而是通过向其添加文本使其更具动态性。
可能有趣的是将省略号附加到单词“正在加载”以获得如下效果:

enter image description here

首先将初始值设置为“正在加载”,然后追加每个点 -

$('#result').html($('#result').html()+'.');
// Loading
// Loading.
// Loading..
// Loading...

那说你也可以拿动画gif并使用:P

答案 1 :(得分:2)

尝试:


setTimeout(function() {
    $('#result').html(data);
}, 3000);

答案 2 :(得分:2)

编辑:更新以添加加载功能。

$("#go").click(function(){ 
   $.post("get.php", {p: 'abc'}, function(data){ 
   window.intervalTimer = setInterval(function(data) {
       if (!window.timeoutCount)
            window.timeoutCount = 0;

            if (++window.timeoutCount > 3) {
                $('#result').html(data);
                clearInterval(window.intervalTimer);
             }
            else
                  $('#result').html("Loading..")
    }, 1000); 
   });
});

答案 3 :(得分:2)

要在JavaScript中延迟执行函数,请使用setTimeout方法。有点像:

var doLater = setTimeout(function(){
alert('I like to wait 5 seconds');
},5000); //delay is stated in ms

在您的情况下,最终会:

$("#go").click(function(){ 
   $.post("get.php", {p: 'abc'}, function(data){ 
   var wait = setTimeout(function(){$('#result').html(data);},3000); 
   });
});

答案 4 :(得分:1)

试试这个:

$("#go").click(function(){ 
   // Show loader here
   $.post("get.php", {p: 'abc'}, function(data){ 
       setTimeout(function () {
           // Hide loader here
           $('#result').html(data);
       }, 3000); 
   });
});

答案 5 :(得分:1)

$("#go").click(function(){ 
  $.post("get.php", {p: 'abc'}, function(data) {  
    $('go').html('Loading.');
    setTimeout("function() {
      $('go').html('Loading..');
    }",1000);
    setTimeout("function() {
      $('go').html('Loading...');
    }",1000);
    $('#result').html(data); 
  }
}