index.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. fetch("/writing/comments/touchscreens")
  2. .then(response => response.json())
  3. .then((response)=>{
  4. if(typeof(response) === "string"){
  5. console.log(response);
  6. }else{
  7. let comments = document.getElementById("comments");
  8. let template = document.getElementById("comment").content.children[0];
  9. let dateOptions = {
  10. month: "long",
  11. day: "numeric",
  12. year: "numeric",
  13. hour: "2-digit",
  14. minute: "2-digit"
  15. };
  16. for(let i = 0; i < response.length; i++){
  17. let comment = template.cloneNode(true);
  18. comment.children[0].children[0].innerText = response[i].name;
  19. comment.children[0].children[1].innerText = new Date(response[i].date).toLocaleString("en-US", dateOptions);
  20. comment.children[1].innerText = response[i].content;
  21. comments.appendChild(comment);
  22. }
  23. }
  24. })
  25. .catch((err)=>{
  26. console.log(err);
  27. });
  28. createComment = ()=>{
  29. event.preventDefault();
  30. let data = {
  31. article: document.getElementById("articleInput").getAttribute("article"),
  32. name: document.getElementById("nameInput").value,
  33. content: document.getElementById("commentInput").value,
  34. date: new Date()
  35. };
  36. fetch("/writing/comments", {
  37. method: "post",
  38. headers: {
  39. "Content-Type": "application/json;charset=utf-8"
  40. },
  41. body: JSON.stringify(data)
  42. })
  43. .then(response => response.json())
  44. .then((response)=>{
  45. if(typeof(response) === "string"){
  46. console.log(response);
  47. }else{
  48. let comments = document.getElementById("comments");
  49. let comment = document.getElementById("comment").content.children[0].cloneNode(true);
  50. let dateOptions = {
  51. month: "long",
  52. day: "numeric",
  53. year: "numeric",
  54. hour: "2-digit",
  55. minute: "2-digit"
  56. };
  57. comment.children[0].children[0].innerText = response.name;
  58. comment.children[0].children[1].innerText = new Date(response.date).toLocaleString("en-US", dateOptions);
  59. comment.children[1].innerText = response.content;
  60. comments.insertBefore(comment, comments.children[1]);
  61. }
  62. })
  63. .catch((err)=>{
  64. console.log(err);
  65. });
  66. }
  67. document.getElementById("createComment").onsubmit = ()=>{createComment()};