Chat.html 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. const 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. async function sendMessage(nick, message){
  24. jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message})
  25. .then(data => data)
  26. }
  27. async function getMessages(){
  28. jsonPost("http://students.a-level.com.ua:10012",{func: "getMessages", messageId: 0})
  29. .then(data => {
  30. let dataRevers = data.data.reverse()
  31. document.getElementById("main").replaceChildren()
  32. for(let el of dataRevers){
  33. let div = document.createElement('div')
  34. div.innerText= `${el.nick}: ${el.message}`
  35. document.getElementById('main').append(div)
  36. }
  37. })
  38. }
  39. getMessages()
  40. async function sendAndCheck(){
  41. sendMessage(document.getElementById("nick").value, document.getElementById("message").value)
  42. await getMessages()
  43. }
  44. function checkLoop(){
  45. setInterval(()=>getMessages(),2000)
  46. }
  47. checkLoop()
  48. </script>
  49. </body>
  50. </html>