18_practic_chat.HTML 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <!DOCTYPE html>
  2. <!-- saved from url=(0025)http://192.168.1.20:5000/ -->
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  6. <title>18_practic_chat</title>
  7. </head>
  8. <body>
  9. <div id="formContainer"></div>
  10. <input type="text" id="nickId" />
  11. <input type="text" id="msgId" />
  12. <button id="sendId">Send msg</button>
  13. <div id="chatId">sdfasfasfvasafvasfabvfasdfbasbfas</div>
  14. <script>
  15. // jsonPost("http://students.a-level.com.ua:10012", {
  16. // func: "addMessage",
  17. // nick: "Sheva",
  18. // message: "++Hi++",
  19. // });
  20. function jsonPost(url, data) {
  21. return new Promise((resolve, reject) => {
  22. var x = new XMLHttpRequest();
  23. x.onerror = () => reject(new Error("jsonPost failed"));
  24. //x.setRequestHeader('Content-Type', 'application/json');
  25. x.open("POST", url, true);
  26. x.send(JSON.stringify(data));
  27. x.onreadystatechange = () => {
  28. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  29. resolve(JSON.parse(x.responseText));
  30. } else if (x.status != 200) {
  31. reject(new Error("status is not 200"));
  32. }
  33. };
  34. });
  35. }
  36. sendId.onclick = function () {
  37. jsonPost("http://students.a-level.com.ua:10012", {
  38. func: "addMessage",
  39. nick: nickId.value,
  40. message: msgId.value,
  41. });
  42. };
  43. //
  44. //
  45. let startMsgId = 0;
  46. let date;
  47. setInterval(() => {
  48. let j = jsonPost("http://students.a-level.com.ua:10012", {
  49. func: "getMessages",
  50. messageId: startMsgId,
  51. }).then((x) => {
  52. startMsgId = x.nextMessageId;
  53. console.log(startMsgId);
  54. shouMsg(x.data);
  55. });
  56. let shouMsg = function (msgArr) {
  57. // console.log(msgArr);
  58. // msgArr.reverse();
  59. msgArr.forEach((element) => {
  60. date = new Date(element.timestamp);
  61. let str =
  62. date.getFullYear() +
  63. "/" +
  64. (date.getMonth() + 1) +
  65. "/" +
  66. date.getDate() +
  67. " " +
  68. date.getHours() +
  69. ":" +
  70. date.getMinutes() +
  71. ":" +
  72. date.getSeconds() +
  73. " " +
  74. element.nick +
  75. ": " +
  76. element.message +
  77. "<br>";
  78. chatId.insertAdjacentHTML("afterbegin", str);
  79. });
  80. };
  81. }, 5000);
  82. </script>
  83. </body>
  84. </html>