1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- <header>Chat</header>
- <body>
- <div>
- <input id="nicknameInp" type="text"><br>
- <input id="messageInp" type="text"><br>
- <button id="sendBtn">Send</button><br><br>
- <div id="chat"></div>
- </div>
- <script>
- /*function jsonPost1(url, data) {
- return new Promise((resolve, reject) => {
- var x = new XMLHttpRequest();
- x.onerror = () => reject(new Error('jsonPost failed'))
- //x.setRequestHeader('Content-Type', 'application/json');
- x.open("POST", url, true);
- x.send(JSON.stringify(data))
- x.onreadystatechange = () => {
- if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
- resolve(JSON.parse(x.responseText))
- }
- else if (x.status != 200) {
- reject(new Error('status is not 200'))
- }
- }
- })
- }*/
- async function jsonPost(url, data) {
- var res = await fetch(url,
- {
- method: "POST",
- body: JSON.stringify(data)
- })
- .then(res => res.json(), () => { throw new Error('jsonPost failed') });
- return res;
- }
- async function getMessages(fromMessId = 0) {
- let a = await jsonPost("http://students.a-level.com.ua:10012", { func: "getMessages", messageId: fromMessId });
- nextMessageId = a.nextMessageId;
- if (fromMessId == 0) {
- chat.textContent = '';
- }
- chat.append(...a.data.map(obj => {
- let chatEl = document.createElement("div");
- let timeEl = document.createElement("div");
- let nickEl = document.createElement("div");
- let messEl = document.createElement("div");
- let brEl = document.createElement("br");
- chatEl.append(timeEl, nickEl, brEl, messEl, brEl);
- var date = new Date(obj.timestamp);
- timeEl.innerText = date.toLocaleString() + " ";
- nickEl.innerText = obj.nick + ": ";
- messEl.innerText = obj.message;
- return chatEl;
- }));
- }
- async function checkLoop(interval) {
- while (true) {
- getMessages(nextMessageId);
- await delay(interval);
- }
- }
- async function sendMessage(nick, message) {
- let res = await jsonPost("http://students.a-level.com.ua:10012", { func: 'addMessage', nick: nick, message: message });
- return res;
- }
- async function sendAndCheck(nick, message) {
- await sendMessage(nicknameInp.value, messageInp.value);
- getMessages(nextMessageId);
- }
- const delay = async (ms) => {
- return new Promise(res => setTimeout(res, ms));
- }
- let nextMessageId = 0;
- sendBtn.onclick = async () => {
- sendAndCheck(nicknameInp.value, messageInp.value);
- }
- checkLoop(5000);
- </script>
- </body>
|