Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
109 lines (85 loc) · 3.02 KB
/
Copy pathscript.js
File metadata and controls
109 lines (85 loc) · 3.02 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
(function() {
const example = document.getElementById('example')
const cw1 = document.getElementById('cw1')
const cw2 = document.getElementById('cw2')
const cw3 = document.getElementById('cw3')
const answer = document.getElementById('answer')
example.addEventListener("click", function() {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(array => {
console.log(array)
answer.innerHTML = JSON.stringify(array);
})
})
cw1.addEventListener("click", function () {
answer.innerHTML = "<p><em>Loading...</em></p>";
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(posts => {
console.log(posts);
let html = "<ul>";
posts.forEach(post => {
html += `<li><strong>${post.title}</strong><br>${post.body}</li>`;
});
html += "</ul>";
answer.innerHTML = html;
})
.catch(error => {
console.error("Błąd pobierania danych:", error);
answer.innerHTML = "<p style='color:red;'>Nie udało się pobrać danych.</p>";
});
}, 1000);
});
cw2.addEventListener("click", function () {
const selectedId = document.getElementById("postSelect").value;
answer.innerHTML = "<p><em>Loading...</em></p>";
fetch(`https://jsonplaceholder.typicode.com/posts/${selectedId}`)
.then(response => response.json())
.then(post => {
console.log(post);
const html = `
<h3>${post.title}</h3>
<p>${post.body}</p>
<p><strong>ID:</strong> ${post.id}</p>
`;
answer.innerHTML = html;
})
.catch(error => {
console.error("Błąd:", error);
answer.innerHTML = "<p style='color:red;'>Nie udało się pobrać posta.</p>";
});
});
cw3.addEventListener("click", function () {
const title = prompt("Podaj tytuł nowego posta:");
const body = prompt("Podaj treść nowego posta:");
if (!title || !body) {
answer.innerHTML = "<p style='color:red;'>Musisz wpisać tytuł i treść posta!</p>";
return;
}
answer.innerHTML = "<p><em>Processing...</em></p>";
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
title: title,
body: body,
userId: 1
})
})
.then(response => response.json())
.then(data => {
console.log("Odpowiedź serwera:", data);
answer.innerHTML = `<p style="color:green;">Dodano nowy post o ID = ${data.id}</p>`;
})
.catch(error => {
console.error("Błąd wysyłania:", error);
answer.innerHTML = "<p style='color:red;'>Nie udało się dodać posta.</p>";
});
}, 1000);
});
})();