main.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. async 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. async function sendMessage(nick, message) {
  19. jsonPost("http://students.a-level.com.ua:10012", {
  20. func: 'addMessage',
  21. nick: nick,
  22. message: message,
  23. author: 'chat'
  24. });
  25. }
  26. const dateToDataTimeLocal = date => (date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, -1);
  27. let timestamp = new Date();
  28. let nextMessageId = 0;
  29. async function getMessages() {
  30. await jsonPost("http://students.a-level.com.ua:10012", {
  31. func: 'getMessages',
  32. messageId: nextMessageId
  33. }).then(res => {
  34. res.data.forEach(el => {
  35. let div = document.createElement('div');
  36. div.innerHTML = `${el.nick} : ${el.message}:<br> ${timestamp.toGMTString()}`;
  37. chat.prepend(div);
  38. nextMessageId++;
  39. console.log(nextMessageId);
  40. });
  41. });
  42. }
  43. send.onclick = async function sendAndCheck() {
  44. sendMessage(nick.value, message.value);
  45. getMessages();
  46. };
  47. async function checkLoop() {
  48. await getMessages().then(() => delay(setTimeout (3000)).then(checkLoop));
  49. }
  50. checkLoop();