main.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. let messageId = 0;
  2. async function sendMessage() {
  3. let data = {
  4. func: 'addMessage',
  5. nick: `${nick.value}`,
  6. message: `${message.value}`,
  7. };
  8. try {
  9. let response = await fetch('http://students.a-level.com.ua:10012', {
  10. method: 'POST',
  11. body: JSON.stringify(data),
  12. });
  13. let result = await response.json();
  14. messageId = result.nextMessageId;
  15. }
  16. catch (err) {
  17. console.log(err);
  18. }
  19. }
  20. function buildChat (obj) {
  21. let arr = obj['data'];
  22. for (let i = 0; i < arr.length; i++) {
  23. const b = document.createElement('b');
  24. const p = document.createElement('p');
  25. chat.prepend(p);
  26. p.append(b);
  27. b.innerHTML = (`${arr[i]['nick']} :`);
  28. p.append(`${arr[i]['message']}`);
  29. }
  30. }
  31. async function getMessages() {
  32. try {
  33. let data = {
  34. func: "getMessages",
  35. messageId: messageId,
  36. };
  37. let response = await fetch('http://students.a-level.com.ua:10012',{
  38. method: 'POST',
  39. body: JSON.stringify(data),
  40. });
  41. let result = await response.json(); console.log(result);
  42. buildChat(result);
  43. }
  44. catch (err) {
  45. console.log(err);
  46. }
  47. }
  48. async function sendAndCheck() {
  49. Promise.all([sendMessage(), getMessages()])
  50. nick.value = '';
  51. message.value = '';
  52. }
  53. sendMes.onclick = sendAndCheck;
  54. setInterval(getMessages, 3000);