longpolling.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. var lastReceived = 0;
  2. var isWait = false;
  3. var fetch = function () {
  4. if (isWait) return;
  5. isWait = true;
  6. $.getJSON("/lp/fetch?lastReceived=" + lastReceived, function (data) {
  7. if (data == null) return;
  8. $.each(data, function (i, event) {
  9. switch (event.Type) {
  10. case 0: // JOIN
  11. if (event.User == $('#uname').text()) {
  12. $("#chatbox li").first().before("<li>You joined the chat room.</li>");
  13. } else {
  14. $("#chatbox li").first().before("<li>" + event.User + " joined the chat room.</li>");
  15. }
  16. break;
  17. case 1: // LEAVE
  18. $("#chatbox li").first().before("<li>" + event.User + " left the chat room.</li>");
  19. break;
  20. case 2: // MESSAGE
  21. $("#chatbox li").first().before("<li><b>" + event.User + "</b>: " + event.Content + "</li>");
  22. break;
  23. }
  24. lastReceived = event.Timestamp;
  25. });
  26. isWait = false;
  27. });
  28. }
  29. // Call fetch every 3 seconds
  30. setInterval(fetch, 3000);
  31. fetch();
  32. $(document).ready(function () {
  33. var postConecnt = function () {
  34. var uname = $('#uname').text();
  35. var content = $('#sendbox').val();
  36. $.post("/lp/post", {
  37. uname: uname,
  38. content: content
  39. });
  40. $('#sendbox').val("");
  41. }
  42. $('#sendbtn').click(function () {
  43. postConecnt();
  44. });
  45. });