teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

JSの記述を回答提示のリンクを参照し変更

2021/02/02 03:16

投稿

fastman
fastman

スコア3

title CHANGED
File without changes
body CHANGED
@@ -29,30 +29,18 @@
29
29
  ```
30
30
 
31
31
  ```javascript
32
- const rap = document.getElementById("rap");
33
-
34
- function addRap() {
32
+ function addRap() {
35
33
  const XHR = new XMLHttpRequest();
36
34
  const time = document.getElementById("time").innerHTML;
37
35
  XHR.open("POST", "/watches", true);
38
- XHR.responseType = "json";
36
+ XHR.setRequestHeader('content-type', 'application/json')
39
- XHR.send(time);
40
- XHR.onload = () => {
37
+ XHR.onreadystatechange = () => {
41
- if (XHR.status != 200) {
42
- alert(`Error ${XHR.status}: ${XHR.statusText}`);
38
+ if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
39
+ const content = XHR.response;
43
- return null;
40
+ console.log(content)
44
41
  }
45
- const content = XHR.response.watch;
46
- const table = document.getElementById("time-table");
47
- const HTML = `
48
- <tr>
49
- <div class="data" data-id=${content.id}>
50
- <td class="date">${content.id}</td>
51
- <td class="time">${content.watch}</td>
52
- </div>
53
- </tr>`;
54
- table.insertAdjacentHTML("beforeend", HTML);
55
42
  };
43
+ XHR.send("watch="+time); //400(Bad Error)
56
44
  }
57
45
 
58
46
  rap.addEventListener('click', (e) => {

1

htmlのid='time'の要素付加、ルーティングの追加、jsのaddEventListener追加

2021/02/02 03:16

投稿

fastman
fastman

スコア3

title CHANGED
File without changes
body CHANGED
@@ -9,6 +9,12 @@
9
9
  ### 該当のソースコード
10
10
 
11
11
  ```new
12
+ <%# タイマーの時間表示 %>
13
+ <div class="stop-watch">
14
+ <p id="time">00:00:00.000</p>
15
+ </div>
16
+
17
+ <%# STARTとSTOPのボタン %>
12
18
  <%= form_with url: watches_path, class: "buttons" do |f| %>
13
19
  <%= f.submit "START", class: "btn", id: "start" %>
14
20
  <%= f.submit "RAP", class: "btn", id: "rap" %>
@@ -23,6 +29,8 @@
23
29
  ```
24
30
 
25
31
  ```javascript
32
+ const rap = document.getElementById("rap");
33
+
26
34
  function addRap() {
27
35
  const XHR = new XMLHttpRequest();
28
36
  const time = document.getElementById("time").innerHTML;
@@ -38,17 +46,31 @@
38
46
  const table = document.getElementById("time-table");
39
47
  const HTML = `
40
48
  <tr>
41
- <td class="time">
49
+ <div class="data" data-id=${content.id}>
42
- ${content.watch}
43
- </td>
50
+ <td class="date">${content.id}</td>
51
+ <td class="time">${content.watch}</td>
44
52
  </div>
45
53
  </tr>`;
46
54
  table.insertAdjacentHTML("beforeend", HTML);
47
55
  };
48
56
  }
57
+
58
+ rap.addEventListener('click', (e) => {
59
+ addRap();
60
+ e.preventDefault();
61
+ }
62
+ });
49
63
  ```
50
64
 
65
+ ```routes
66
+ Rails.application.routes.draw do
67
+ devise_for :users
68
+
69
+ resources :watches, only: [:index, :new, :create]
70
+ end
71
+ ```
51
72
 
73
+
52
74
  `addEventListner`でクリックしたときに`addRap()`を発火させています。
53
75
 
54
76