index.html 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <link rel="stylesheet" href="./style.css">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <input type="text" id="nick">
  11. <input type="text" id="mess">
  12. <button id="btn">submit</button>
  13. <div id="chat-history">
  14. </div>
  15. <script>
  16. function jsonPost(url, data) {
  17. return new Promise((resolve, reject) => {
  18. var x = new XMLHttpRequest();
  19. x.onerror = () => reject(new Error('jsonPost failed'))
  20. //x.setRequestHeader('Content-Type', 'application/json');
  21. x.open("POST", url, true);
  22. x.send(JSON.stringify(data))
  23. x.onreadystatechange = () => {
  24. if (x.readyState == XMLHttpRequest.DONE && x.status == 200){
  25. resolve(JSON.parse(x.responseText))
  26. }
  27. else if (x.status != 200){
  28. reject(new Error('status is not 200'))
  29. }
  30. }
  31. })
  32. }
  33. let btn = document.querySelector('button')
  34. let myNick = document.querySelector('#nick')
  35. let myMess = document.querySelector('#mess')
  36. let chatHistory = document.querySelector('#chat-history')
  37. btn.onclick = () => {
  38. let nickValue = myNick.value;
  39. let myMessValue = myMess.value;
  40. jsonPost("http://students.a-level.com.ua:10012", {
  41. func: 'addMessage',
  42. nick: `${nickValue}`,
  43. message: `${myMessValue}`
  44. })
  45. myMessValue = '';
  46. }
  47. jsonPost("http://students.a-level.com.ua:10012", {func: "getMessages", messageId: 2900}).then(r => {
  48. for (let i in r.data) {
  49. chatHistory.innerHTML += `${r.data[i].nick}: ${r.data[i].message} </br>`
  50. }
  51. })
  52. </script>
  53. </body>
  54. </html>