main.js 1.9 KB

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