如何在队列中存储ajax值

时间:2012-01-19 09:23:49

标签: javascript ajax jquery

我想使用 jQuery.ajax()显示来自我的数据库的一些数据(即每个数据包含一个标题和描述),我希望这个过程定期完成,例如 setInterval(func,5000)

现在我真正需要的是一个js容器(一个数组,一个变量,无论如何),我可以将这些项存储到另一个函数中,我希望它们每隔2秒显示一次。

所以,换句话说:

  • 如果愿意,我们必须有两个功能和一个容器。 ajax函数每5秒触发一次,并将其数据(如果有)附加到容器(队列)中。
  • 另一方面,第二个函数每2秒显示一次容器的内容,当然会从容器中删除显示的项目。

我该如何实现?

3 个答案:

答案 0 :(得分:2)

var queue = [];

function ajaxCall() {
  $.when($.ajax(...)).done(function(data) {
     ///assuming your data json's outermost structure is an array
     while(data[0]) {
        queue.push(data.shift());
     }
  })
}

function publisher() {
   var item = queue.shift();
   if(item) {
      //do your gubbins here
   }
}

setInterval(ajaxCall,5000);

setInterval(publisher, 2000);

答案 1 :(得分:0)

为什么不使用数组。它可以存储一个字符串,一个对象......

看看这个精彩的博客post

如果您需要排队,这post可能对您有帮助....

答案 2 :(得分:0)

首先,设置一个像这样的容器:

<div id="container">
 <ul>
 </ul>
</div>

然后,在你的.js:

//step 1. define global Array to hold the values
$(document).ready(function(){
  var items = new Array();

  //step 3. call the ajax every 5 second
  var updateInterval = setInterval(function() {
    get_the_data();
  //don't forget to empty the array
        items = [];

   }, 5000);

  //step 4. so now, with the data got refresh every 5 second, you just have to append this data into container every 2 second. use the .html method
 //logically, in first two times invoke to this method (4 seconds) the container would get same data from array, but in third invocation (at 6 seconds) the container get the fresh one, and so on...
  var insertToContainer = setInterval(function() {
    for(i=0;i<items.length;i++){
      $('#container ul').html('<li>' + items[i] + '</li>')                  
   }                
    }, 2000);

});

//step 2. set up your ajax call
function get_the_data()
{
  $.ajax({
     //set your ajax code here...
     success:function(data){
        //on success put the data into the global array
        for(i=0;i<data.length;i++){
             items.push(data[i]);
        }
     }
  });
}

我希望这对您的项目有用。干杯:-) PS:坦率地说,我不知道为什么你想要这样的实现(我的意思是,2个不同的更新函数具有不同的间隔值),更简单的方法是每2秒只使用一次调用ajax调用,只要显示它在容器中使用.html,但这只是我的意见,它应该是你的应用程序背后更复杂的逻辑。 : - )