123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
- </head>
- <body>
- <input id="nick" type="text"><br>
- <input id="message" type="text"><br>
- <button id="button" type="button" onclick=sendAndCheck()>Отправить</button>
- <main id="main"></main>
- <script >
- function jsonPost (url, data){
- return fetch(url, {method: 'POST',body: JSON.stringify(data)})
- .then(result => {
- if (result.status === 200) {
- return result.json()
- } else {
- throw new Error('Error')
- }
- }).catch(error => {console.log(error)})
- }
- function sendMessage(nick, message){
- jsonPost("http://students.a-level.com.ua:10012", {func: 'addMessage', nick: nick, message: message})
- }
-
- async function getMessages(){
- let data= await jsonPost("http://students.a-level.com.ua:10012",{func: "getMessages", messageId: 0})
- function update (data) {
- let dataRevers = data.data.reverse()
- document.getElementById("main").replaceChildren()
- for(let el of dataRevers){
- let div = document.createElement('div')
- div.innerText= `${el.nick}: ${el.message}`
- document.getElementById('main').append(div)
- }
- }
- update(data)
- }
- getMessages()
- function sendAndCheck(){
- sendMessage(document.getElementById("nick").value, document.getElementById("message").value)
- getMessages()
- }
- const delay = ms => new Promise(ok => setTimeout(() => ok(ms), ms))
-
- async function checkLoop(){
- while(true){
- await delay(2000)
- getMessages()
- }
- }
- checkLoop()
- </script>
- </body>
- </html>
|