index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. function jsonPost(url, data)
  2. {
  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('inputName')
  20. let msg = document.getElementById('inputMsg')
  21. let send = document.getElementById('send')
  22. let chat = document.getElementById('chat')
  23. let messageId = 0;
  24. async function sendMessage(nick , message ){
  25. await jsonPost("http://students.a-level.com.ua:10012", {
  26. func: 'addMessage',
  27. nick: login.value,
  28. message: msg.value})
  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)