index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. function jsonPost(url, data) {
  2. return new Promise((resolve, reject) => {
  3. var x = new XMLHttpRequest();
  4. x.onerror = () => reject(new Error('jsonPost failed'))
  5. //x.setRequestHeader('Content-Type', 'application/json');
  6. x.open("POST", url, true);
  7. x.send(JSON.stringify(data))
  8. x.onreadystatechange = () => {
  9. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  10. resolve(JSON.parse(x.responseText))
  11. }
  12. else if (x.status != 200) {
  13. reject(new Error('status is not 200'))
  14. }
  15. }
  16. })
  17. }
  18. let login = document.getElementById('inputName')
  19. let msg = document.getElementById('inputMsg')
  20. let send = document.getElementById('send')
  21. let chat = document.getElementById('chat')
  22. let messageId = 0;
  23. async function sendMessage(nick, message) {
  24. await jsonPost("http://students.a-level.com.ua:10012", {
  25. func: 'addMessage',
  26. nick: login.value,
  27. message: msg.value
  28. })
  29. }
  30. async function getMessages() {
  31. jsonPost("http://students.a-level.com.ua:10012", {
  32. func: "getMessages", messageId: 0
  33. }).then((a) => {
  34. showChat(a.data, chat)
  35. })
  36. }
  37. function showChat(data, container) {
  38. let sortedData = data.sort((a, b) => b.timestamp - a.timestamp)
  39. for (let message of sortedData) {
  40. let div = document.createElement('div')
  41. let spanName = document.createElement('b')
  42. let spanMsg = document.createElement('span')
  43. let spanTime = document.createElement('mark')
  44. let time = new Date(message.timestamp)
  45. container.appendChild(div)
  46. div.appendChild(spanName)
  47. div.appendChild(spanMsg)
  48. div.appendChild(spanTime)
  49. spanName.innerHTML = message.nick + ': '
  50. spanMsg.innerHTML = message.message + ' '
  51. spanTime.innerHTML = time.toGMTString()
  52. }
  53. }
  54. async function sendAndCheck() {
  55. sendMessage();
  56. getMessages();
  57. msg.value = ""
  58. }
  59. btn.onclick = () => {
  60. return sendAndCheck()
  61. }
  62. setInterval(getMessages, 5000)