forked from vladkozlenko/JsInterLink
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
45 lines (42 loc) · 1.44 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
window.onload = init;
var StudentsUrl = 'http://localhost:3000/students';
function init() {
loadStudents().then(renderStudents);
var form = document.getElementById("addNew");
form.addEventListener('submit', (event) => {
event.preventDefault();
AddNewStudent()
.then(loadStudents)
.then(renderStudents);
})
}
function renderStudents(students){
let studentElement = document.getElementById('template-student');
let templateContent = studentElement.content.getElementById('post');
let studentsList = document.getElementById('students');
studentsList.innerHTML = '';
for (let st of students) {
let studentClone = templateContent.cloneNode(true);
updateStudentElement(studentClone, st);
studentsList.appendChild(studentClone);
}
}
function loadStudents(){
return fetch(StudentsUrl).then(response => response.json());
}
function AddNewStudent(){
let stName = document.getElementById("studentName").value;
let stKnowledge = document.getElementById("studentKnowledge").value;
return fetch(StudentsUrl, {
method: "POST",
body: JSON.stringify({name: stName,knowledge: stKnowledge}),
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
}
})
}
function updateStudentElement(element, st) {
element.querySelector('h1').innerText = st.name;
element.querySelector('p').innerText = st.knowledge;
}