Chat.html 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <input id="nick" type="text"><br>
  9. <input id="message" type="text"><br>
  10. <button id="button" type="button" onclick=sendAndCheck()>Отправить</button>
  11. <main id="main"></main>
  12. <script >
  13. function jsonPost (url, data){
  14. return fetch(url, {method: 'POST',body: JSON.stringify(data)})
  15. .then(result => {
  16. if (result.status === 200) {
  17. return result.json()
  18. } else {
  19. throw new Error('Error')
  20. }
  21. }).catch(error => {console.log(error)})
  22. }
  23. function sendMessage(nick, message){
  24. jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message})
  25. }
  26. async function getMessages(){
  27. let data= await jsonPost("http://students.a-level.com.ua:10012",{func: "getMessages", messageId: 0})
  28. function update (data) {
  29. let dataRevers = data.data.reverse()
  30. document.getElementById("main").replaceChildren()
  31. for(let el of dataRevers){
  32. let div = document.createElement('div')
  33. div.innerText= `${el.nick}: ${el.message}`
  34. document.getElementById('main').append(div)
  35. }
  36. }
  37. update(data)
  38. }
  39. getMessages()
  40. function sendAndCheck(){
  41. sendMessage(document.getElementById("nick").value, document.getElementById("message").value)
  42. getMessages()
  43. }
  44. const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
  45. async function checkLoop(){
  46. while(true){
  47. await delay(2000)
  48. getMessages()
  49. }
  50. }
  51. checkLoop()
  52. </script>
  53. </body>
  54. </html>