index.js 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. createComment = ()=>{
  27. event.preventDefault();
  28. let data = {
  29. article: document.getElementById("articleInput").getAttribute("article"),
  30. name: document.getElementById("nameInput").value,
  31. content: document.getElementById("commentInput").value,
  32. date: new Date()
  33. };
  34. fetch("/writing/comments", {
  35. method: "post",
  36. headers: {
  37. "Content-Type": "application/json;charset=utf-8"
  38. },
  39. body: JSON.stringify(data)
  40. })
  41. .then(response => response.json())
  42. .then((response)=>{
  43. if(typeof(response) === "string"){
  44. console.log(response);
  45. }else{
  46. let comments = document.getElementById("comments");
  47. let comment = document.getElementById("comment").content.children[0].cloneNode(true);
  48. let dateOptions = {
  49. month: "long",
  50. day: "numeric",
  51. year: "numeric",
  52. hour: "2-digit",
  53. minute: "2-digit"
  54. };
  55. comment.children[0].children[0].innerText = response.name;
  56. comment.children[0].children[1].innerText = new Date(response.date).toLocaleString("en-US", dateOptions);
  57. comment.children[1].innerText = response.content;
  58. comments.insertBefore(comment, comments.children[1]);
  59. }
  60. })
  61. .catch((err)=>{
  62. console.log(err);
  63. });
  64. }
  65. document.getElementById("createComment").onsubmit = ()=>{createComment()};