js.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. function jsonPost(url, data) {
  2. return new Promise((resolve, reject) => {
  3. var x = new XMLHttpRequest();
  4. x.onerror = () => reject(new Error("jsonPost failed"));
  5. //x.setRequestHeader('Content-Type', 'application/json');
  6. x.open("POST", url, true);
  7. x.send(JSON.stringify(data));
  8. x.onreadystatechange = () => {
  9. if (x.readyState == XMLHttpRequest.DONE && x.status == 200) {
  10. resolve(JSON.parse(x.responseText));
  11. } else if (x.status != 200) {
  12. reject(new Error("status is not 200"));
  13. }
  14. };
  15. const chat = document.querySelector("#chat");
  16. chat.style.display = "flex";
  17. chat.style.flexDirection = "column-reverse";
  18. const div = document.createElement("div");
  19. div.style.display = "flex";
  20. div.style.justifyContent = "space-between";
  21. div.style.alignItems = "center";
  22. div.style.margin = "5px";
  23. const p = document.createElement("p");
  24. p.style.margin = "5px";
  25. div.innerText = `${data.nick}: ${data.message}`;
  26. p.innerText = new Date(data.timestamp);
  27. console.log(data.timestamp);
  28. div.appendChild(p);
  29. chat.appendChild(div);
  30. });
  31. }
  32. btn.onclick = () => {
  33. jsonPost("http://students.a-level.com.ua:10012", {
  34. func: "addMessage",
  35. nick: inputNick.value,
  36. message: inputMessage.value,
  37. });
  38. };
  39. let messageId = 0;
  40. jsonPost("http://students.a-level.com.ua:10012", {
  41. func: "getMessages",
  42. messageId,
  43. }).then((d) => {
  44. messageId = d.nextMessageId;
  45. for (const key of d.data) {
  46. const div = document.createElement("div");
  47. div.style.display = "flex";
  48. div.style.justifyContent = "space-between";
  49. div.style.alignItems = "center";
  50. div.style.margin = "5px";
  51. const p = document.createElement("p");
  52. p.style.margin = "5px";
  53. div.innerText = `${key.nick}: ${key.message}`;
  54. p.innerText = new Date(key.timestamp);
  55. div.appendChild(p);
  56. chat.appendChild(div);
  57. }
  58. console.log(d.data);
  59. });