简单的聊天工作但一遍又一遍地显示相同的消息

时间:2015-08-29 00:27:41

标签: javascript jquery ajax chat long-polling

我的问题是如何在相同的消息上反复停止循环?

这是我的代码:

waitForMsg();
setInterval(waitForMsg, 5000);

function waitForMsg() {
  $.ajax({
    url: CI_ROOT + 'welcome/getMessage',
    type: "GET",
    dataType: 'json',
    async: true,
    cache: false,

    success: function(data) {
      $.each(data, function(key, value) {

        var msg_id = value.msg_id;
        var timestamp = value.posted_at;
        var user_msg = value.msg;
        var user_name = value.name;


        $(".chat_log").append(
          "<p data-id=" + msg_id + ">" + "<b>" + user_name + "</b>" + ': ' + user_msg + ' | Posted: ' + "<span data-livestamp=" + timestamp + "></span>" + ', msg ID: ' + msg_id + "</p>"
        );


      });
    }
  });
}

以下是我得到的 "welcome/getMessage"

[{
    "name": "Dima",
    "msg": "i don't know i feel bad today :(",
    "posted_at": "2015-08-29 02:50:31",
    "msg_id": "12"
  },
  {
    "name": "toma",
    "msg": "whats wrong?",
    "posted_at": "2015-08-29 02:48:59",
    "msg_id": "11"
  },
  {
    "name": "toma",
    "msg": "hey",
    "posted_at": "2015-08-29 02:46:11",
    "msg_id": "10"
  }
]

结果是:

Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10
Dima: i don't know i feel bad today :( | Posted: 3 hours ago, msg ID: 12
toma: whats wrong? | Posted: 3 hours ago, msg ID: 11
toma: hey | Posted: 3 hours ago, msg ID: 10

我需要以某种方式比较客户端和或服务器端的msg ID。

我很乐意感谢任何帮助!

迪马克。

1 个答案:

答案 0 :(得分:0)

这是我的新解决方案。

https://jsfiddle.net/dannyjhonston/tvcy4k6r/1/

...更新

$(function() {
  var messages = [{
    "name": "Dima",
    "msg": "i don't know i feel bad today :(",
    "posted_at": "2015-08-29 02:50:31",
    "msg_id": "12"
  }, {
    "name": "toma",
    "msg": "whats wrong?",
    "posted_at": "2015-08-29 02:48:59",
    "msg_id": "11"
  }, {
    "name": "toma",
    "msg": "hey",
    "posted_at": "2015-08-29 02:46:11",
    "msg_id": "10"
  }];

  $("#btnSendMessage").on("click", function() {
    // Adds new message object to message's array.
    messages.push({
      name: "NewUser",
      msg: $("#txtMessage").val(),
      posted_at: new Date(),
      msg_id: new Date().getTime()
    });
    console.log(messages);
  });

  var oldCountMessages = messages.length; // Previously, you need to save the messages's length.

  var newMessageIndex = 0; // Declare a numeric variable to use like new index to show a new chat message.

  // You need to print the messages, only once.
  for (var i = 0; i < messages.length; i++) {
    $("#chatMessages").append("<div class=\"chat\"><span class=\"user\">" + messages[i].name + "</span><br /> " + messages[i].msg + "</div>");
  }
  // Self-looping function to show check if there are new messages.
  (function loop() {
    // Checking if there are new messages.
    if (messages.length > oldCountMessages) {
      // Initializing newMessageIndex with the new message index, to show it.
      newMessageIndex = messages.length - 1;
      // Printing only the new message.
      $("#chatMessages").append("<div class=\"chat\"><span class=\"user\">" + messages[newMessageIndex].name + "</span><br /> " + messages[newMessageIndex].msg + "</div>");
    }
    // Updating oldCountMessages variable for the next verification in the looping function.
    oldCountMessages = messages.length;
    setTimeout(loop, 1000); // Checking the server every second.	
  })();
});
#chatMessages {
  font-family: sans-serif;
  font-size: 0.8em;
}

.chat {
  background-image: linear-gradient(#BED4E6, #FFFFFF);
  border: solid 1px #84A8D6;
  border-radius: 5px;
  margin: 5px;
  padding: 10px;
}

.chat:hover {
  background-image: linear-gradient(#FFFFFF, #BED4E6);
}

.user {
  background-color: inherit;
  color: #224577;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="txtMessage" type="text" value="" />
<button id="btnSendMessage" type="button">Send message</button>
<hr />
<div id="chatMessages"></div>