使用ajax检索mysql数据,然后操作它


Retrieving mysql data using ajax and then manipulating it

我的问题在这个网站上有部分解决方案,但不是一个完整的答案。

在我的wordpress主页上,我显示了在我们的webapp中回答的问题数量的计数器。这是使用jQuery和AJAX从php文件中检索问题数来显示的,并且与此代码一起工作得很好。

jQuery(document).ready(function() {
function load() {
jQuery.get('/question_count.php', function(data) {jQuery('#p1').html( data );  });
}
load();
setInterval(load,10000);
});

是否有一种方法显示计数到检索到的新数字,而不是立即显示它?

像这样?

function countTo(n) {
    var p = $("#p1"),
        c = parseInt(p.html(), 10) || 0,
        dir = (c > n ? -1 : 1);    // count up or down?
    if (c != n) {
        p.html((c + dir) + "");
        setTimeout(function() {
            countTo(n);
        }, 500);
    }
}

在你的成功处理程序

中调用它
jQuery.get('/question_count.php', function(data) {
    var n = parseInt(data, 10);
    countTo(n);
});
示例

您将需要执行setInterval事件,以便人眼可以看到计数。这可能是一个问题,如果你最终达到足够的问题,计数需要很长时间才能到达终点。

代码看起来像这样:

function load(){
   jQuery.get('/question_count.php', function(data){
      var curr = 0;
      var max = parseInt(data);
      var interval = setInterval(function(){
        if(curr==max){
           clearInterval(interval);
        }
        jQuery('#p1').html( curr );
        curr+=1; //<-- if the number of questions gets very large, increase this number
      },
      10 //<-- modify this to change how fast it updates
      });
   }
}