如何使用jQuery和AJAX从服务器获取和附加最新消息?

时间:2015-06-14 15:21:53

标签: javascript jquery ajax

我正在开发我的第一个简单的聊天应用程序,这个问题让我陷入困境。我知道我要做的是什么,但我最终过度思考它。

基本上,我有这个heroku服务器:

http://tiy-fee-rest.herokuapp.com/collections/blabberTalk

每当有人发送消息时,都会将其添加到此数组中。

我的问题:

我在一个设定的时间间隔内,每2秒运行一次getNewestMessages函数。当此setInterval正在工作并且有人发送消息时,它将继续追加他们每2秒发送的最后一条消息。如果我禁用setInterval并在一个单独的浏览器选项卡中自己调用getNewestMessages函数,则似乎不会发生这种情况。 我想这样做,以便在setInterval处于活动状态时,不会经常将最近发送的消息重新附加到DOM。

这是我用来检查最近消息的功能。它非常臃肿,抱歉:

  getNewestMessages: function() {
$.ajax({
  url: http://tiy-fee-rest.herokuapp.com/collections/blabberTalk,
  method: 'GET',
  success: function (data) {
    // Finds Id of most recent message displayed in the DOM
    var recentId = $('.message').last().data('id');
    var prevMostRecent = 0;
    var newMostRecent = [];
    jQuery.each(data, function(idx,el){
      if (el._id === recentId) {
        // if one of the messages on the server has an Id equal to
        // one of the messages in the DOM, it saves its index in a var
        prevMostRecent = idx;
      }
    });
    jQuery.each(data, function(idx,el){
      if (idx < prevMostRecent) {
        // if there are messages on the server with a lower index than
        // the most recent message in the DOM, it pushes them to a new
        // array. Basically, creates a new array of any messages newer
        // than the last one displayed in the DOM.
        newMostRecent.push(el);
      }
    });
    for (var i = 0; i < newMostRecent.length; i++) {
      console.log(newMostRecent[i]);
      if (newMostRecent[i]._id === $('.message').last().data('id')) {
        // My attempt at trying to remove the last DOM message from
        // the array of newer messages. My main issue was that this
        // whole function would keep appending the most recent message
        // over and over again.
        var result = _.without(newMostRecent, newMostRecent[i]);
        console.log('MESSAGE TO BE EXCLUDED: ', newMostRecent[i]);
        // If the array of newer messages contained the most recent
        // DOM message, it removes it and sends it to be appended.
        page.appendNewestMessages(result);
      }
    }
    // If the array of newer messages DOESN'T contain the most recent
    // DOM message, it just sends the whole array normally.
    page.appendNewestMessages(newMostRecent);
  },
  error: function (err) {

  }
});
}

这是追加功能:

appendNewestMessages: function(messagesToAppend) {
console.log(messagesToAppend.reverse());

_.each(messagesToAppend.reverse(), function(el, idx, arr) {
  var newMessage = {
    content: el.content,
    timestamp: el.timestamp,
    author: el.author,
    userIcon: el.userIcon
  }
  $.ajax({
    url: page.url,
    method: 'POST',
    data: newMessage,
    success: function (data) {
      page.addOneMessageToDOM(data);
    },
    error: function (err) {
      console.log("error ", err);
    }

  });
})
}

任何人都可以帮助我了解如何从服务器获取最新消息并将其附加到DOM而不重复吗?这让我疯了。

感谢您的帮助。

0 个答案:

没有答案