├── index.html └── main.js /index.html: -------------------------------------------------------------------------------- 1 | // index.html 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Document 10 | 11 | 12 | 13 | 14 | 15 |

Danh Sách Bạn Bè

16 | 17 |
18 | 19 | 20 |
21 |
22 | 23 | 24 |
25 |
26 | 27 |
28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /main.js: -------------------------------------------------------------------------------- 1 | //main.js 2 | var link = 'http://localhost:3000/courses' 3 | var html = [] 4 | var listUsers = document.getElementById('users') 5 | 6 | function start() { 7 | getUsers() 8 | handleUsers() 9 | } 10 | 11 | start() 12 | 13 | function getUsers() { 14 | fetch(link) 15 | .then(function (response) { 16 | return response.json() 17 | }) 18 | .then(renderUsers) 19 | } 20 | 21 | function renderUsers(users) { 22 | html = users.map(function (user) { 23 | return ` 24 |
  • 25 |

    ${user.name}

    26 |

    ${user.age} Years Old

    27 | 28 | 29 |
  • 30 | ` 31 | }) 32 | listUsers.innerHTML = html.join('') 33 | } 34 | 35 | function addUser(user) { 36 | var options = { 37 | method: 'POST', 38 | headers: { 39 | 'Content-Type': 'application/json', 40 | }, 41 | body: JSON.stringify(user), 42 | } 43 | fetch(link, options) 44 | .then(function (response) { 45 | return response.json() 46 | }) 47 | .then(function () { 48 | getUsers() 49 | }) 50 | } 51 | 52 | function handleUsers() { 53 | var btnAdd = document.querySelector('#add') 54 | btnAdd.onclick = function () { 55 | var name = document.querySelector('input[name="name"]').value 56 | var age = Number(document.querySelector('input[name="age"]').value) 57 | var user = { 58 | name: name, 59 | age: age, 60 | } 61 | addUser(user) 62 | } 63 | } 64 | 65 | function btnDelete(id) { 66 | var options = { 67 | method: 'DELETE', 68 | headers: { 69 | 'Content-Type': 'application/json', 70 | }, 71 | } 72 | fetch(link + '/' + id, options) 73 | .then(function (response) { 74 | return response.json() 75 | }) 76 | .then(function () { 77 | var listItem = document.querySelector('.listItem-' + id) 78 | listItem.remove() 79 | }) 80 | } 81 | 82 | function btnRename(id) { 83 | var name = document.querySelector('input[name="name"]').value 84 | var age = Number(document.querySelector('input[name="age"]').value) 85 | var user = { 86 | name: name, 87 | age: age, 88 | } 89 | var options = { 90 | method: 'PATCH', 91 | headers: { 92 | 'Content-Type': 'application/json', 93 | }, 94 | body: JSON.stringify(user), 95 | } 96 | fetch(link + '/' + id, options) 97 | .then(function (response) { 98 | return response.json() 99 | }) 100 | .then(function () { 101 | getUsers() 102 | }) 103 | //reset name & age inpute 104 | document.querySelector('input[name="name"]').value = '' 105 | document.querySelector('input[name="age"]').value = '' 106 | } 107 | --------------------------------------------------------------------------------